Coder Perfect

With jQuery, how can I select an element by name?


I’m trying to expand and hide a table column. When I pick the td> elements by class but not by name, jQuery appears to hide them.

For example:

$(".bold").hide(); // Selecting by class works.
$("tcol1").hide(); // Selecting by name does not work.

Take note of the HTML code below. For all rows, the second column has the same name. How might I use the name attribute to construct this collection?

  <td name="tcol1" class="bold"> data2</td>
  <td name="tcol1" class="bold"> data2</td>
  <td name="tcol1" class="bold"> data2</td>

Asked by T.T.T.

Solution #1

The jQuery attribute selection can be used as follows:

$('td[name="tcol1"]')   // Matches exactly 'tcol1'
$('td[name^="tcol"]' )  // Matches those that begin with 'tcol'
$('td[name$="tcol"]' )  // Matches those that end with 'tcol'
$('td[name*="tcol"]' )  // Matches those that contain 'tcol'

Answered by Jon Erickson

Solution #2

The [attribute name=value] method can be used to pick any attribute. Here’s an example:

var value = $("[name='nameofobject']");

Answered by user2804791

Solution #3

If you have something along the lines of:

<input type="checkbox" name="mycheckbox" value="11" checked="">
<input type="checkbox" name="mycheckbox" value="12">

All of this can be read like this:

jQuery("input[name='mycheckbox']").each(function() {
    console.log( this.value + ":" + this.checked );

The snippet:

Answered by Andreas L.

Solution #4

You could use the old method of getting the array of elements by name and passing it to jQuery.

Note that the “name” attribute should only be used for checkbox or radio inputs.

Alternatively, you could simply add a selection class to the elements. (This is exactly what I’d do.)

Answered by Your Friend Ken

Solution #5

Using the name element in jQuery, you may get the name value from an input field by:

Answered by Shrikant D

Post is based on