Get attribute name value of <input>

Viewed 485408

How to get the attribute name value of a input tag using jQuery. Please help.

<input name="xxxxx" value="1">
11 Answers

using value get input name

 $('input[value="1"]').attr('name');

using id get input name

 $('input[class="id"]').attr('name');
   $('#id').attr('name');

using class get input name

 $('input[value="classname"]').attr('name');
   $('.classname').attr('name');  //if classname have unique value

If you're dealing with a single element preferably you should use the id selector as stated on GenericTypeTea answer and get the name like $("#id").attr("name");.

But if you want, as I did when I found this question, a list with all the input names of a specific class (in my example a list with the names of all unchecked checkboxes with .selectable-checkbox class) you could do something like:

var listOfUnchecked = $('.selectable-checkbox:unchecked').toArray().map(x=>x.name);

or

var listOfUnchecked = [];
$('.selectable-checkbox:unchecked').each(function () {
    listOfUnchecked.push($(this).attr('name'));
});

Pass class to input tag and access the name value by using class.

<input class="test-class" name='xxxxx' value=1>

<script>
    $('.test-class').attr('name');
</script>

Or you can also access the value using id.

<input id="test-id" name='xxxxx' value=1>

<script>
    $('#test-id').attr('name');
</script>
Related