Tuesday, May 14, 2013

Accessing form elements by name with jQuery

There are a variety of ways to access elements with jQuery including by the name property of form elements (the name="" part of <input name="foo">). This can be useful so you don't have to assign an id to each and every form element as well as a name which is needed to pass the form value to the next page.

Example form

Here's a snippet of a form for the following examples with first_name and last_name fields in a form.

<form ... >
    ....
    <input type="text" name="first_name" value="" />
    <input type="text" name="last_name" value="" />
    ....
</form>

Selecting by name
To select the "first_name" text input form element do this:
$("input[name=first_name]");
For example to display the value in an alert window do this:
alert( $("input[name=first_name]").val() );

Source : http://www.electrictoolbox.com/jquery-form-elements-by-name/

0 Comments:

Post a Comment