• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Accessing form elements by name with jQuery

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() );

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.

Check Out These Related posts:

  1. Style HTML form elements optgroup and option with CSS in Chrome
  2. Style HTML form elements optgroup and option with CSS in Firefox
  3. Style HTML form elements optgroup and option with CSS in Internet Explorer
  4. Style HTML form elements optgroup and option with CSS in Opera

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap