KJS
KJS

Reputation: 1214

Get dynamic radio ID and value (jQuery)

We have dynamic ID's generated from a database like this:

<input type="radio" id="brand1" value="1">
<input type="radio" id="brand1" value="2">
----
<input type="radio" id="brand2" value="1">
<input type="radio" id="brand2" value="2">

How can I get/alert, through a click on a radio button, which ID it is?

(I guess my error is in the first line: 'input#brand'.)

$('input#brand').live('click',function() { 
    var radiovalue = $('input[name=brand + id]:checked').val()
    alert(radiobuttonID + radiovalue);
});

Upvotes: 1

Views: 2043

Answers (4)

Musa
Musa

Reputation: 97672

Use the attribute-starts-with-selector, this will select all input with id that start with brand.

$('input[id^=brand]').live('click',function() { 
    alert(this.id + ' ' + this.value);
});

Also as of jQuery 1.7 .live() was deprecated, use .on() instead. Also ids should be unique, in your markup you have multiple elements with the same id.

Upvotes: 1

bozdoz
bozdoz

Reputation: 12860

You would use something like this to get id:

$('input[id^=brand]').live('click',function() {
    alert($(this).attr('id'));
});​

and this to get value:

$('input[id^=brand]').live('click',function() {
    alert($(this).attr('value'));
});​

Notice that we can put a live click handler on all of the elements that start with (^=) "brand".

See JSFiddle

Upvotes: 1

Semyon Vyskubov
Semyon Vyskubov

Reputation: 986

Correct your selector please. $('input#brand') means that you looking for INPUT with exact id "brand".

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

$(document).on('click', 'input[type=radio]' , function() {

     alert('Radio Button ID  is : ' + this.id + ' - Value is : ' + this.value);
})

Also make sure you have unique id's on the page..

It's better to assign a single class to all the radio buttons on the page for which you want to handle this event..

$(document).on('click', '.myradio' , function() {

         alert('Radio Button ID  is : ' + this.id + ' - Value is : ' + this.value);
    })

Doing so will make you code cleaner and easier to understand

Upvotes: 1

Related Questions