By T.T.T.


2009-07-10 01:05:38 8 Comments

Have a table column I'm trying to expand and hide:

jQuery seems to hide the td elements when I select it by class but not by element's name.

For example, why does:

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

Note the HTML below, the second column has the same name for all rows. How could I create this collection using the name attribute?

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

13 comments

@Jon Erickson 2009-07-10 01:21:08

You can use the jQuery attribute selector:

$('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'

@HPWD 2012-02-03 17:52:25

Just out of curiosity, how would one write this as NOT tcol1, like what if they wanted to hide the columns other than the columns named, tcol1?

@Jon Erickson 2012-07-09 06:36:53

@Varun - you can just omit the td... for example $('[name^=tcol]') will match all elements that have an attribute 'name' with a value that starts with 'tcol'

@akki 2014-12-17 11:14:41

I had to use it like $('td [name=tcol1]') - without the space between td and [] it returned me NULL.

@mareoraft 2015-10-17 16:51:42

@DougMolineux Actually, he is matching the prefix of a name.

@beginner 2015-12-22 07:34:50

there should be quote after the equal = sign. $('td[name=\'tcol1\']')

@R K Sharma 2015-12-23 09:55:29

what if I have to select from multiple names ex. $('input[name=abc,xyz,tsq,etc]')?

@JohannesB 2016-05-11 11:51:47

@HPWD you would use the :not selector, $("td:not([name='tcol1'])") for example. You can see it at this fiddle

@HPWD 2016-05-11 12:41:50

@Rsauxil thanks for the fiddle. I wasn't sure of the syntax.

@dheeraj Kumar 2017-01-09 19:38:45

can anyone fiddle example ?

@felix Antony 2017-04-27 15:22:02

Example: $('input[name$="Phone"]').blur(function () { var t = $(this).val().replace(/ /g, "").toUpperCase(); if ($(this).val().length != 0) { $(this).val(t.substring(0, 3) + " " + t.substring(3, 6)); }; });

@DigM 2019-01-25 17:49:22

Would this work if there were braces in the name so for example input[name=boldthemes_theme_listing-working_time[0][start]]?

@user8555937 2019-11-08 11:00:08

Fore further reference, if you want to access a child element by name which is nested within an element you're accessing by ID, note the space between ID and selector: $('#td_id [name="tcol"]')

@Pratyush Goyal 2019-06-19 07:08:53

You can use the function:

get.elementbyId();

@barbsan 2019-06-19 07:39:38

OP wanted to get by name, not id. And what is get.elementbyId()? Did you mean document.getElementById()?

@barbsan 2019-06-19 07:47:09

No, he is asking to select an element by name.

@Steve Childs 2015-02-23 12:16:59

Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

That should restrict jQuery from searching the "world".

Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

@HoldOffHunger 2018-06-27 18:01:09

Somewhat wordy answer, but this is fundamentally the correct overall approach.

@Steve Childs 2018-06-28 15:38:05

May be a bit wordy, but better to have a bit extra explanation and reasoning behind a suggestion than a single line that explains little! ;) Its useful when someone is new to something and trying to understand why a) it works and b) how it works

@Chris J 2017-11-20 19:27:54

You forgot the second set of quotes, which makes the accepted answer incorrect:

$('td[name="tcol1"]') 

@relytmcd 2018-06-13 23:57:08

for example if the field name is 'td[name="nested[fieldName]"]'

@HoldOffHunger 2018-06-27 18:03:55

This is very true. Newer versions of jQuery (v. 3.2.1) are much more likely to fail when encountering a attribute-based selector element without proper quoting.

@Shrikant D 2015-06-15 05:52:03

You can get the name value from an input field using name element in jQuery by:

var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ 
console.log(firstname);
console.log(lastname);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1" id="form1">
  <input type="text" name="firstname" value="ABCD"/>
  <input type="text" name="lastname" value="XYZ"/>
</form>

@SharpC 2015-10-06 15:58:50

+1 The only example given which selects a name field including type and limits the results to within an id section.

@Kar.ma 2016-05-19 16:34:19

I agree. You can have multiple forms in your page, and restricting to the proper one is a good idea.

@Andreas L. 2014-07-09 18:34:15

If you have something like:

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

You can read all like this:

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

The snippet:

jQuery("input[name='mycheckbox']").each(function() {
  console.log( this.value + ":" + this.checked );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="mycheckbox" value="11" checked="">
<input type="checkbox" name="mycheckbox" value="12">

@Your Friend Ken 2009-07-11 05:25:01

You could get the array of elements by name the old fashioned way and pass that array to jQuery.

function toggleByName() {
  var arrChkBox = document.getElementsByName("chName");
  $(arrChkBox).toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
    <title>sandBox</title>
  </head>
  <body>
    <input type="radio" name="chName"/><br />
    <input type="radio" name="chName"/><br />
    <input type="radio" name="chName"/><br />
    <input type="radio" name="chName"/><br />
    <input type="button" onclick="toggleByName();" value="toggle"/>
  </body>
</html>

note: the only time you would have a reason to use the "name" attribute should be for checkbox or radio inputs.

Or you could just add another class to the elements for selection.(This is what I would do)

function toggleByClass(bolShow) {
  if (bolShow) {
    $(".rowToToggle").show();
  } else {
    $(".rowToToggle").hide();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
    <title>sandBox</title>
  </head>
  <body>
    <table>
      <tr>
        <td>data1</td>
        <td class="bold rowToToggle">data2</td>
      </tr>
      <tr>
        <td>data1</td>
        <td class="bold rowToToggle">data2</td>
      </tr>
      <tr>
        <td>data1</td>
        <td class="bold rowToToggle">data2</td>
      </tr>
    </table>
    <input type="button" onclick="toggleByClass(true);" value="show"/>
    <input type="button" onclick="toggleByClass(false);" value="hide"/>
  </body>
</html>

@Guest 2016-04-27 18:47:53

Here's a simple solution: $('td[name=tcol1]')

@user6139189 2016-03-31 12:51:10

You can use any attribute as selector with [attribute_name=value].

$('td[name=tcol1]').hide();

@itsnikolay 2015-10-16 16:27:15

Frameworks usually use bracket names in forms, like:

<input name=user[first_name] />

They can be accessed by:

// in JS:
this.querySelectorAll('[name="user[first_name]"]')

// in jQuery:
$('[name="user[first_name]"]')

// or by mask with escaped quotes:
this.querySelectorAll("[name*=\"[first_name]\"]")

@kscius 2015-03-25 20:27:52

I've done like this and it works:

$('[name="tcol1"]')

https://api.jquery.com/attribute-equals-selector/

@user2804791 2013-09-22 19:07:44

Any attribute can be selected using [attribute_name=value] way. See the sample here:

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

@Afzaal Ahmad Zeeshan 2013-09-22 19:11:32

but you should use the above code, so that you donot miss up with the qoutations! Good luck and welcome to Stackoverflow community :)

@Pranav 2014-09-22 06:28:10

This is not working at least for me - But following statement works var value = $("[name=nameofobject]");

@Huangism 2015-03-25 20:41:48

It's surprising this get 17 upvotes when this came 4 years after the original accepted answer

@Chris Sprague 2015-06-09 06:03:17

21 upvotes now...maybe it's because the answer is less confusing than 'td[name=tcol1]', especially since the td is not required and hence leads people like me down the wrong path

@René Sackers 2015-11-11 13:29:30

Thank you, this is actually what I was looking for. I need to select ANY element with the given name. @Pranav currently in jQuery, it works with, and without quotes. Probably changed that in some version between then and now.

@Sunish Menon 2016-07-30 07:48:52

My input names had a [] like this: <input name="itemid[]">. So this answer worked more perfectly than the accepted answer, thanks to the proper usage of quotes.

@CalebHC 2009-07-10 01:09:39

You can get the element in JQuery by using its ID attribute like this:

$("#tcol1").hide();

@T.T.T. 2009-07-10 01:10:32

Matches a single element only

@CalebHC 2009-07-10 01:14:23

Sorry about that. Just do what Ben S said.

@T.T.T. 2009-07-10 01:21:16

Yes that is true about the ID. As far as selecting by name, I think there was a post up here referring to Selectors/attributeEquals which was helpful.

@nckbrz 2014-11-02 15:29:41

Maybe the question has been edited, but he is asking for name reference now, but yes single elements can use the id selector

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6260159 View
  • 7816 Score
  • 93 Answer
  • Tags:   javascript arrays

33 Answered Questions

36 Answered Questions

30 Answered Questions

[SOLVED] jQuery scroll to element

41 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

65 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

13 Answered Questions

[SOLVED] How can I select an element with multiple classes in jQuery?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

Sponsored Content