Home » Jquery » How can I select an element by name with jQuery?

How can I select an element by name with jQuery?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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 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>
Answers:

you can use the 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'

Questions:
Answers:

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

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

Questions:
Answers:

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

Questions:
Answers:

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>

Questions:
Answers:

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>

Questions:
Answers:

I’ve done like this and it works:

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

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

Questions:
Answers:

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]\"]")

Questions:
Answers:

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

Questions:
Answers:

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

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

Questions:
Answers:

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

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

Questions:
Answers:

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, 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 seperately 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); 
}

Questions:
Answers:

To hide all td which has name “tcol1”

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

Questions:
Answers:
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="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="text" name="chName"/><br />
    <input type="button" onclick="toggleByName();" value="toggle"/>
  </body>
</html>

Questions:
Answers:
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var a= $("td[name=tcol3]").html();
    alert(a);

});

</script>


<table border="3">
<tr>    
    <td>data1</td>
    <td name="tcol1" class="bold"> data2tcol1</td>
</tr>
<tr>    
    <td>data1</td>
    <td name="tcol2" class="bold"> data2tcol2</td>
</tr>  
<tr>    
    <td>data1</td>
    <td name="tcol3" class="bold"> data2tcol3</td>
</tr>
</table>

This is the Code which can be helpful.