Community Documentation

HOWTO: Get the value inside a form element

Last updated July 25, 2008. Created by aj045 on July 25, 2008.
Log in to edit this page.

You've already heard it many times, but indeed jQuery provides a sleek way of dealing with the Document Object Model. Form elements are no exception to jQuery, though they have a few slight differences from regular HTML elements. Think of it this way: form elements are interactive-- users can submit information to them. But with, say, a DIV or a P element, there is no implicit interactive nature to it. It is just... there.
If you know jQuery already, you may know that the text() or html() methods can be used to get the text content of an element. However, you should really only use text() or html() on non-interactive HTML elements like IMG or DIV or P. If you want the value of a form element, consider using the val() function. Example:

<script type="text/javascript">
$(document).ready(function() {
  $("#my_button").click(function() {
    // show the text that is in the textarea element
    // when the button is clicked.
    alert($("#my_textarea").val());
  });
});
</script>

The above code will work on the following HTML:
<form>
  <textarea id="my_textarea"></textarea>
  <input type="button" value="Click me!" id="my_button" />
</form>

If you would like additional information, see the jQuery documentation, especially these links:

About this page

Drupal version
Drupal 5.x
Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.