1563

I 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 the element’s name.

For example:

$(".bold").hide(); // Selecting by class works.
$("tcol1").hide(); // Selecting by name does not work. [Edit: this is NOT selecting by name! This is selecting by element type.]

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>
OutstandingBill
2,9661 gold badge31 silver badges41 bronze badges
asked Jul 10, 2009 at 1:05
3
  • 11
    Question does not match content. ID and name are different attributes and are selected differently Commented Aug 22, 2011 at 13:08
  • 16
    It's against W3C standards to have elements with the same ID; i.e. duplicate IDs are a no no. Commented Feb 17, 2013 at 1:28
  • The CSS specification includes a new column combinator, so soon you can simply select document.querySelectorAll("td || col.secondColumn") if you have a <colgroup><col class="firstColumn"/><col class="secondColumn"/></colgroup>. Commented Mar 18, 2021 at 11:31

15 Answers 15

2777

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'
Sebastian Simon
19.8k8 gold badges61 silver badges88 bronze badges
answered Jul 10, 2009 at 1:21
Sign up to request clarification or add additional context in comments.

2 Comments

@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'
[name="fk_item_id[${clone_id}]"] did the magic
346

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

var value = $("[name='nameofobject']");
matpie
17.6k10 gold badges64 silver badges84 bronze badges
answered Sep 22, 2013 at 19:07

Comments

88

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">

Al Foиce ѫ
4,34112 gold badges44 silver badges51 bronze badges
answered Jul 9, 2014 at 18:34

Comments

34

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>

Al Foиce ѫ
4,34112 gold badges44 silver badges51 bronze badges
answered Jul 11, 2009 at 5:25

Comments

32

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>

Al Foиce ѫ
4,34112 gold badges44 silver badges51 bronze badges
answered Jun 15, 2015 at 5:52

Comments

22

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]\"]")
answered Oct 16, 2015 at 16:27

Comments

17

I've done like this and it works:

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

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

Paweł Tomkiel
1,9842 gold badges21 silver badges39 bronze badges
answered Mar 25, 2015 at 20:27

Comments

11

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

$('td[name="tcol1"]') 
answered Nov 20, 2017 at 19:27

2 Comments

for example if the field name is 'td[name="nested[fieldName]"]'
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.
5

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

$('td[name=tcol1]').hide();
answered Mar 31, 2016 at 12:51

Comments

5

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

Barry Michael Doyle
10.8k33 gold badges98 silver badges162 bronze badges
answered Apr 27, 2016 at 18:47

Comments

5

Performance

Today (2020年06月16日) I perform tests for chosen solutions on MacOs High Sierra on Chrome 83.0, Safari 13.1.1 and Firefox 77.0.

Conclusions

Get elements by name

  • getElementByName (C) is fastest solution for all browsers for big and small arrays - however I is probably some kind of lazy-loading solution or It use some internal browser hash-cache with name-element pairs
  • mixed js-jquery solution (B) is faster than querySelectorAll (D) solution
  • pure jquery solution (A) is slowest

Get rows by name and hide them (we exclude precalculated native solution (I) - theoretically fastest) from comparison - it is used as reference)

  • surprisingly the mixed js-jquery solution (F) is fastest on all browsers
  • surprisingly the precalculated solution (I) is slower than jquery (E,F) solutions for big tables (!!!) - I check that .hide() jQuery method set style "default:none" on hidden elements - but it looks that they find faster way of do it than element.style.display='none'
  • jquery (E) solution is quite-fast on big tables
  • jquery (E) and querySelectorAll (H) solutions are slowest for small tables
  • getElementByName (G) and querySelectorAll (H) solutions are quite slow for big tables

enter image description here

Details

I perform two tests for read elements by name (A,B,C,D) and hide that elements (E,F,G,H,I)

  • small table - 3 rows - you can run test HERE
  • big table - 1000 rows - you can run test HERE

Snippet below presents used codes

//https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery#
// https://jsbench.me/o6kbhyyvib/1
// https://jsbench.me/2fkbi9rirv/1
function A() {
 return $('[name=tcol1]');
}
function B() {
 return $(document.getElementsByName("tcol1"))
}
function C() {
 return document.getElementsByName("tcol1")
}
function D() {
 return document.querySelectorAll('[name=tcol1]')
}
function E() {
 $('[name=tcol1]').hide();
}
function F() {
 $(document.getElementsByName("tcol1")).hide();
}
function G() {
 document.getElementsByName("tcol1").forEach(e=>e.style.display='none'); 
}
function H() {
 document.querySelectorAll('[name=tcol1]').forEach(e=>e.style.display='none'); 
}
function I() {
 let elArr = [...document.getElementsByName("tcol1")];
 let length = elArr.length
 for(let i=0; i<length; i++) elArr[i].style.display='none';
}
// -----------
// TEST
// -----------
function reset() { $('td[name=tcol1]').show(); } 
[A,B,C,D].forEach(f=> console.log(`${f.name} rows: ${f().length}`)) ;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>This snippet only presents used codes</div>
<table>
 <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>
</table>
<button onclick="E()">E: hide</button>
<button onclick="F()">F: hide</button>
<button onclick="G()">G: hide</button>
<button onclick="H()">H: hide</button>
<button onclick="I()">I: hide</button><br>
<button onclick="reset()">reset</button>

Example results on Chrome

enter image description here

answered Jun 16, 2020 at 20:33

1 Comment

great info, but a lot of stuff that don't answer the question, it's just related knowledge
4

2 more examples:

<input type="text" name="foo">
<input type="text" name="foo[bar]">

with:

$('[name="foo"]');
$('[name="foo\\[bar\\]"]');

snippet:

$('#copy').on('click', () => {
 let $from = $('[name="foo"]');
 let $to = $('#result-1');
 $to.val($from.val());
 $from = $('[name="foo\\[bar\\]"]');
 $to = $('#result-2');
 $to.val($from.val());
});
<script src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
<p>
 <input type="text" name="foo" value="copy name='foo'">
 <input type="text" disabled id="result-1" placeholder="i'm disabled">
</p>
<p>
 <input type="text" name="foo[bar]" value="copy name='foo[bar]'">
 <input type="text" disabled id="result-2" placeholder="i'm disabled">
</p>
<input type="button" id="copy" value="copy values">

answered Mar 29, 2023 at 18:00

Comments

2

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
21.3k11 gold badges123 silver badges147 bronze badges
answered Feb 23, 2015 at 12:16

Comments

-7

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

$("#tcol1").hide();
answered Jul 10, 2009 at 1:09

5 Comments

OP asked by name, not id
Why does this answer appear at the top?
@Marcus because it's the most rad answer of them all.
@dylanh724 the question was originally about finding by name.
You didn't answer the question, please, refrain from adding unnecessary answers that are not what the user asked for.
-25

You can use the function:

get.elementbyId();
mastisa
2,1413 gold badges25 silver badges42 bronze badges
answered Jun 19, 2019 at 7:08

2 Comments

OP wanted to get by name, not id. And what is get.elementbyId()? Did you mean document.getElementById()?
No, he is asking to select an element by name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.