Jennifer Michelle Jennifer Michelle - 2 months ago 13
jQuery Question

Jquery nested each functions

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!

Answer

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
        }
      }


    }

  }