Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery dynamically added checkbox .attr("checked",true) not working

Tags:

jquery

Based on some data I'm cloning a div with a checkbox and check it if the data value is "True" then append to a target div.

using jquery 1.5.2

IE8 works in compatibility mode, doesn't work otherwise. FF doesn't work.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="scripts/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {          
            // test data
            var data = [{ "CB": "True" }, { "CB": "False"}];

            var theClone = $("#clone").clone(true);
            var temp = "";

            if (data !== null) {
                $.each(data, function (i, d) {
                    var cb = theClone.find('.cbClass');

                    if (d.CB === "True") { 
                        //cb.attr("checked","checked"); //doesn't work
                        //cb.val(true); //doesn't work
                        //cb.attr("checked", true); //doesn't work

                    }

                    temp += theClone.html();
                });
            }
            $("#target").append(temp);    
        });
    </script>
</head>
<body>
<div id="target">
    <div id="clone" class="cloneClass" style="display:none">
    <div class="container">
        <input type="checkbox" class="cbClass" />
    </div>
</div>
</div>

</body>
</html>
like image 264
dm80 Avatar asked Dec 27 '22 22:12

dm80


1 Answers

Try this out, it appears that using .attr("checked", "checked") does not effect the html, try using the direct javascript method setAttribute and removeAttribute

$.each(data, function(i, d) {
    var cb = theClone.find('.cbClass');
    if (d.CB === "True") {
        cb.get()[0].setAttribute("checked", "checked");
    }
    else{
         cb.get()[0].removeAttribute("checked");
    }
    temp += theClone.html();
});

Also notice since you are always working with theClone you need to use removeAttribute since the previous iteration modified the element.

Code example on jsfiddle

Update

If you deal directly with jQuery objects it appears it will work in IE9, chrome, FF, and IE compatibility mode.

var temp = [];

if (data !== null) {
    $.each(data, function(i, d) {
        var theClone = $("#clone div").clone(true);
        var cb = theClone.find('.cbClass');
        if (d.CB === "True") {
            cb.attr("checked", "checked");
        }
        temp.push(theClone);
    });
}

$.each(temp, function(i, item) {
    $("body").append(item);
});

Code example on jsfiddle

like image 80
Mark Coleman Avatar answered Jan 04 '23 23:01

Mark Coleman