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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With