pekcheng
pekcheng

Reputation: 364

Html radio with same name in different div

Radio buttons are grouped together by name. However, is it not possible to have individual radio buttons with same name, but categorised into different divisions?

 <div id='image1'>
   <input type="radio" name="type"/> JPEG
   <input type="radio" name="type"/> BMP
   <input type="radio" name="type"/> PNG
 </div>
 <div id='image2'>
   <input type="radio" name="type"/> JPEG
   <input type="radio" name="type"/> BMP
   <input type="radio" name="type"/> PNG
 </div>

Theoretically it's an incorrent approach. Just needed some double confirmation.

I have a radio change event listenning to it,

 $('input:radio[name="type"]').change(function(){
      // do something
 });

How can I fix it accordingly ?

Upvotes: 0

Views: 1541

Answers (1)

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

As the others have mentioned you cannot do that. If you have control over the HTML you can append a unique identifier to the name attribute like this:

HTML:

<div id='image1'>
    <input type="radio" name="image1type" />JPEG
    <input type="radio" name="image1type" />BMP
    <input type="radio" name="image1type" />PNG</div>
<div id='image2'>
    <input type="radio" name="image2type" />JPEG
    <input type="radio" name="image2type" />BMP
    <input type="radio" name="image2type" />PNG</div>

and then modify your javascript like this:

$('input:radio[name$="type"]').change(function () {
    // do something
    console.log('change for ' + $(this).parent().attr('id'));
});

Demo here: http://jsfiddle.net/robschmuecker/rCbaL/

Upvotes: 2

Related Questions