Dr. Atul Tiwari
Dr. Atul Tiwari

Reputation: 1085

Get element id from class name in jquery

I found similar questions, but difference in my case is, I have same class name in multiple radio-buttons, and I want to figure out which radio button is clicked? HTML code is like -

<input type='radio' value='1' id='country_1' name='countries' class='option_selector'>
<label for='country_1'>India</label>
<input type='radio' value='2' id='country_2' name='countries' class='option_selector'>
<label for='country_2'>USA</label>
<input type='radio' value='3' id='country_3' name='countries' class='option_selector'>
<label for='country_3'>UK</label>

<input type='radio' value='1' id='city_1' name='cities' class='option_selector'>
<label for='city_1'>Jaipur</label>
<input type='radio' value='2' id='city_2' name='cities' class='option_selector'>
<label for='city_2'>Delhi</label>
<input type='radio' value='3' id='city_3' name='cities' class='option_selector'>
<label for='city_3'>Mumbai</label>

My jQuery is like -

$('.option_selector').click(function () {
    var id = $('.option_selector').attr('id');
    alert(id);
});

But it always returns the id of 1st element having the class name option_selector

Upvotes: 1

Views: 272

Answers (4)

jnoreiga
jnoreiga

Reputation: 2175

I'm not sure what you are monitoring the click events for but a simple way to get the options that are selected is:

$('.option_selector:checked');

This will give you a list of only the checked checkboxes. Then you can go through and get the ids or whatever you would like.

$('.option_selector:checked').each(function() {
var $currentcheckbox = $(this);
});

This is an alternative to monitoring all of the click events.

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

As has been pointed out, the key is to use the keyword, this to keep the context within the current radio button. Thus var id = $('.option_selector').attr('id'); should be:

var id = this.id;

However, the one event that is appropriate to use with radio buttons (and checkboxes) is the change event. You only want to fire the code when there's been a change:

$('.option_selector').change(function() {
    var id = this.id;
    alert(id);
});

Or:

$('.option_selector').on('change', function() {
    var id = this.id;
    alert(id);
});

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

You need to use this to refer clicked element

$('.option_selector').click(function() {
  var id = this.id;
  // or var id = $(this).attr('id');
  alert(id);
});

Upvotes: 4

David
David

Reputation: 218808

You're re-selecting all matching elements here:

$('.option_selector').attr('id');

But since the click handler runs in the context of the element which was clicked, you can just use the this keyword to refer to that element:

$(this).attr('id');

or possibly, even more simply:

this.id;

Upvotes: 4

Related Questions