-2

I want to have all the id's of the radio buttons with the same name

I've tried using this

<input type="radio" name="user" id="Jason" value="Jason11">
<input type="radio" name="user" id="Adam"  value="Adam11">

var names= $('input[type=radio][name="user"]').attr('id')
console.log(names)

but this only shows the first id

Is there a way to show both id's?

Seki12
  • 1
  • 2

2 Answers2

2

Use each() iteration.

var names = [];
$('input[type=radio][name=user]').each(function(i, elm) {
     names.push($(elm).prop('id'))
})
console.log(names)
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="radio" name="user" id="Jason" value="Jason11">
<input type="radio" name="user" id="Adam"  value="Adam11">

Update:

As per your comment if you want to get the nth element's ID then can use eq(n - 1) function. Example code for getting second element's ID:

var name = $('input[type=radio][name=user]:eq(1)').prop('id')
console.log(name);
MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

Use map() to create an array

var names = $('input[type=radio][name="user"]').map(function() {
  return this.id;
}).get();

console.log(names)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="user" id="Jason" value="Jason11">
<input type="radio" name="user" id="Adam" value="Adam11">
charlietfl
  • 170,828
  • 13
  • 121
  • 150