Reputation: 1733
I have cloned some radio buttons, attached to each row in a page. When I try to loop through them to 'check' the correct radio button on page load, it is only working on the vary last one.
Here is the problem isolated on Codepen: http://codepen.io/trinzia/pen/dpOoRk
var buttonpanel = $("#sectionbuttons");
$('section').each(attachRowButtons);
function attachRowButtons(i, elem) {
var newpanel = buttonpanel.clone(true, true);
$(elem).append(newpanel);
newpanel.removeAttr("id").removeClass('collapse');
var d = $(elem).data('type');
if (d) {
newpanel.find('input[name="myradio"]:radio').each(getType);
function getType(i, elem) {
var n = $(this).val().search(d);
if (n > -1) {
$(this).prop("checked", "checked"); //correct
}
}
}
}
If you look at the codepen, you will see that, even though each row gets a match, only the last radio button set is ever checked. I need to get the value checked correctly (radio checked=checked), one per each row.
Thanks!
Upvotes: 0
Views: 111
Reputation: 18997
Already you have two correct answers. Yes the issue was with the same named radio buttons
. Since you already figured it out with other answers, I would like to make the code simpler while checking the radio button.
You can make your code this simple inside your if(d)
block
if ( d ) {
newpanel.find( 'input[name="myradio"][value="'+ d +'"]')
.prop("name","random" + i)
.prop("checked", "checked");
}
You can use a value
selector instead of looping and trying to find the one matching with the value.
Upvotes: 1
Reputation: 1820
update the js please Link : http://codepen.io/anon/pen/rrWVEr
var buttonpanel = $("#sectionbuttons");
$('section').each( attachRowButtons );
function attachRowButtons (i, elem) {
var index=i; //Add this line .......................................
var newpanel = buttonpanel.clone(true, true);
$(elem).append( newpanel );
newpanel.removeAttr( "id" ).removeClass('collapse');
var d = $(elem).data('type');
if ( d ) {
//Checked="checked" on radio buttons at page load
newpanel.find( 'input[name="myradio"]:radio').each(getType);
function getType(i,elem) {
$(this).prop("name", "myradio"+index); //Add this line .......................................
var n = $(this).val().search(d);
if ( n > -1 ) {
$(this).prop("checked", "checked"); //correct
}
}
}
}
Upvotes: 2
Reputation: 100
The reason you only ever have 1 radio button checked is because they all share the same name attribute "myradio". You will need to change the names of the cloned inputs before they can be a separate group.
You could do that with something like:
var newpanel = buttonpanel.clone(true, true);
newpanel.find('input').each(function() {
$(this).attr('name', 'anothername');
});
And later when you find the input elements within the panels, you should change:
newpanel.find('input[name="myradio"]:radio').each(getType);
to
newpanel.find('input:radio').each(getType);
Upvotes: 2