Accessing form elements by name with jQuery
Posted June 23rd, 2009 in Javascript
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() );
To speed up the process so your jQuery code doesn't have to traverse the entire DOM looking for the element you could define the <form> itself with an ID (e.g. <form id="myform">) and do this:
alert( $("#myform input[name=first_name]").val() );
Deprecated @
Prior to jQuery 1.3 you could do this:
$("input[@name=first_name]")
However the @ syntax was deprecated in jQuery 1.2 and removed in jQuery 1.3, so don't use it when using jQuery 1.2 and up.
Related posts:
- jQuery Form Selectors (Friday, January 1st 2010)
- Clear a form with jQuery (Friday, June 19th 2009)
- How to check and uncheck a checkbox with jQuery (Friday, November 14th 2008)
- How to get and set form element values with jQuery (Thursday, November 13th 2008)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
