Search code examples
javascripthtmljqueryradio-buttonchecked

Radio Input gets unchecked after jQuery html operation


I'm getting an extremely weird error. My radio button gets unchecked after doing the following operations:

    var $page = $('[data-shortcode-page="' + shortcode + '"]', $webrock).html();

    //CHECKED
    console.log($('[data-shortcode-page="' + shortcode + '"] :checked', $webrock).length) 
    $('.webrock-page-content', $addPage).replaceWith($page);
    //UNCHECKED
    console.log($('[data-shortcode-page="' + shortcode + '"] :checked', $webrock).length)

Does anyone know why this is happening? Here's a jsFiddle: http://jsfiddle.net/mVB2q/1/

Thank you very much!


Solution

  • You are cloning a radio group with the same name. You need to update the name of the cloned radio group. Here is a simple solution where I am hardcoding in "test1" for the new group name, but you may want to modify it to fit your needs:

    var shortcode = 'object';        
    
    var $page = $('[data-shortcode-page="' + shortcode + '"]');
    
    console.log($('[data-shortcode-page="' + shortcode + '"] :checked').length);
    
    //after cloning the radio buttons, find radio buttons and update the name attribute.
    $('.webrock-page-content').html($page.clone().find("input[type='radio']").attr("name", "test1").end().html());
    console.log($('[data-shortcode-page="' + shortcode + '"] :checked').length);
    

    Updated fiddle.