jquery dynamic select radio button (form reset issue)

dynamic, javascript, jquery, radio-button

Solution

Have you tried using `.prop()` ?

$('#ddShowBar').prop('checked', true);

http://api.jquery.com/prop/

Attributes vs. Properties The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

There more: in your example you're generating multiple `ID` elements and duplicate attr: name for your radio groups. Every new group needs a different `name` for it's radios than the ones in the previous group. Easy doable with a coulter `c` variable:

in this example the radios in the first group will have names: `txtradio0` ; than the next group radios: `txtradio1` etc...

To maintain the other rows radios checked you just need to change the group NAME attributes:

DEMO

var r = ['Pie','Bar','Line','Area','Scatter'];
var c = 0;  // a group counter // set to 1 if you want

function populateWithRadio(){

    var rB = "<div class='radiobuttons'>";
    for(var i=0; i< r.length; i++){         // create radios
        rB += "<input type='radio' class='ddShow"+ r[i] +"' name='txtradio"+ c +"' value='"+r[i]+"'/>"+ r[i] ;
    }
    rB += "</div></br></br>";

    c++;                         // increase Group counter 
    return rB;                   // returns the generated HTML to append
}


$('#div1').append( populateWithRadio() );
$('#div2').append( populateWithRadio() );

$(document).on("click", '.radiobuttons input', function () {
    alert( 'CLASS: '+ this.className +'\n NAME: '+ this.name );
});

Problem

I was trying to select radio button dynamically using ``` $('#dashboard2 #dbMainPanel #bar2 #ddShowBar').attr('checked', true); ``` But this one will cause `form.reset()` failure. Since I have many buttons in the page and i don't use form tag when i select ``` $('#dashboard1 #dbMainPanel #bar1 #ddShowBar').attr('checked', true); ``` all the other radio buttons get reset. How to avoid this? and keep the existing radio buttons in the page as selected and then dynamically change the current one. - First click `pie` in `div1` - Then click `bar` in `div2` In this scenario I want `pie` in `div1` and `bar` in `div2` to be selected Fiddle Fiddle2

Original source