How can I select an element by name with jQuery?
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.
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>
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'
Any attribute can be selected using [attribute_name=value]
way.
See the sample here:
var value = $("[name='nameofobject']");
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">