Adding content to a text input via a link click.


/ Published in: jQuery
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Title</title>
  6. <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.min.js"></script>
  7. </head>
  8. <body>
  9.  
  10. <h1>Approach 1</h1>
  11. <a id="td_msg">Click <b>here</b></a>
  12. <input type="text" id="target" />
  13. <script type="text/javascript">
  14.  
  15. /* Always use the 'document ready' code with jQuery. Here's why: http://docs.jquery.com/How_jQuery_Works#Launching_Code_on_Document_Ready */
  16. $(document).ready(function(){
  17.  
  18. /* This script will REPLACE the input's content every time you click on the link. */
  19. $('#td_msg').click(function(){ // Whenever the user clicks on the link with id 'td_msg',
  20. var thisValue = $(this).text(); // store the text inside of this link as a string value,
  21. var thisTarget = $('#target'); // store the target element that you want to manipulate,
  22. thisTarget.val(thisValue); // and finally assign the link's content as the value of the text input.
  23. return false; // This line will prevent the default link behavior.
  24. });
  25.  
  26. });
  27. </script>
  28.  
  29. <hr />
  30.  
  31. <h1>Approach 2</h1>
  32. <a id="td_msg2">Click <b>here</b></a>
  33. <input type="text" id="target2" />
  34. <script type="text/javascript">
  35.  
  36. $(document).ready(function(){
  37.  
  38. /* This script will APPEND the input's content every time you click on the link. */
  39. $('#td_msg2').click(function(){ // Whenever the user clicks on the link with id 'td_msg2',
  40. var thisValue = $(this).text(); // store the text inside of this link as a string value,
  41. var thisTarget = $('#target2'); // store the target element that you want to manipulate,
  42. var targetVal = thisTarget.val(); // store the target element's value,
  43. thisTarget.val(targetVal+' '+thisValue); // and finally assign the link's content as the value of the text input.
  44. return false; // This line will prevent the default link behavior.
  45. });
  46.  
  47. });
  48. </script>
  49.  
  50. </body>
  51. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.