Prals
Prals

Reputation: 606

The "checked" attribute of checkbox does not get enabled if the html is created dynamically

I have created a listview containing checkbox. On few of the list items I wanted the checkbox to be checked. The listview is created dynamically as the content comes from the server.

I have the following jsfiddle code. http://jsfiddle.net/praleedsuvarna/rN28z/

Can you please help me solve this problem? Thanks in advance

below is an example of my dynamic list content where the 2nd and 3rd checkbox is set to "checked"

$(document).on('pageshow', '#index', function(){     
    var list = '<li>'+
    '   <div class="checkBoxLeft">'+
    '       <input type="checkbox" name="checkbox-0" id="checkbox-0" class="hidden-checkbox"/>'+
    '   </div>  '+
    '   <a href="item1.html" class="detailListText">item1</a>'+
    '</li>'+
    '<li>'+
    '   <div class="checkBoxLeft">'+
    '       <input type="checkbox" name="checkbox-0" id="checkbox-0" class="hidden-checkbox" checked="checked"/>'+
    '   </div>'+
    '   <a href="item1.html" class="detailListText">item2</a>'+
    '</li>'+
    '<li>'+
    '   <div class="checkBoxLeft">'+
    '       <input type="checkbox" name="checkbox-0" id="checkbox-0" class="hidden-checkbox" checked="checked"/>'+
    '   </div>                     '+
    '   <a href="item1.html" class="detailListText">item3</a>'+
    '</li>'

    $("#viewdata").html(list);
    $("#viewdata").listview("refresh");
});

below is my html page

<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
            <a href="#second" class="ui-btn-right">Next</a>
        </div>

        <div data-role="content">
            <ul data-role="listview" data-theme="a" id="viewdata">
            </ul>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>   
</body>

Upvotes: 4

Views: 808

Answers (1)

dfsq
dfsq

Reputation: 193301

Fixed and a little cleaned up version: http://jsfiddle.net/rN28z/6/

I moved this code:

$('input[type="checkbox"]').each(function() {
    $(this).parent('.checkBoxLeft').addClass(this.checked ? 'checked' : 'not-checked');
});

inside pageshow handler. You were calling it on pagebeforeshow and by that time your HTML had not been yet populated.

Upvotes: 3

Related Questions