Check radio button from pageinit does not work

1.2k Views Asked by At

The following code does not work, the radio button is not checked. Any idea why?

I've tried attr('checked', 'checked') as well.

<html>
<head>      
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>      
    <script type="text/javascript">
    $(document).bind("pageinit", function () {           
        $('#radio-pet-2a').attr('checked', true);
    });         
    </script>
  </head>
 <body>

<div data-role="content">

    <ul data-role = "listview">

        <li>
        <fieldset data-role="controlgroup">
        <legend>Choose a pet:</legend>
             <input type="radio" name="radio-pet" id="radio-pet-1a" value="choice-1"   />
             <label for="radio-pet-1a">Cat</label>

             <input type="radio" name="radio-pet" id="radio-pet-2a" value="choice-2"  />
             <label for="radio-pet-2a">Dog</label>

             <input type="radio" name="radio-pet" id="radio-pet-3a" value="choice-3"  />
             <label for="radio-pet-3a">Hamster</label>

             <input type="radio" name="radio-pet" id="radio-pet-4a" value="choice-4"  />
             <label for="radio-pet-4a">Lizard</label>
    </fieldset>
        </li>

    </ul>
</div>

</body>
</html>
3

There are 3 best solutions below

0
Yang On BEST ANSWER

I've figured out how to let it work:

    $(document).bind("pageinit", function () {           
        $('#radio-pet-2a').attr('checked', true);
        $("input[type='radio']").checkboxradio("refresh"); 
    });     
1
Marcelo De Polli On

You need to update the rendering by using button('refresh') after changing the logical setting:

$(document).bind("pageinit", function () {           
    $('#radio-pet-2a').attr('checked', true).button('refresh');
});
0
Chanraksmey On

Try the prop method to set attribute check of radio button and then refresh radio button.

$(document).bind("pageinit", function () {           
    $('#radio-pet-2a').prop("checked", true).checkboxradio("refresh");
});