I have a situation where I get the following in JavaScript:
$('<input type="checkbox" name="checkbox1" value="12345">').prop('checked',true);
The above doesn't check the checkbox at all. Also tried:
$('<input type="checkbox" name="checkbox1" value="12345">').attr('checked','checked');
When I do this, I get the value:
$('<input type="checkbox" name="checkbox1" value="12345">').val();
The following is contained in an array:
<input type="checkbox" name="checkbox1" value="12345">
So I usually call above as:
$(data[0]).val();
Why doesn't checking/unchecking using prop or attr work?
The checkbox IS checked.
var elem = $('<input type="checkbox" name="checkbox1" value="12345">').prop('checked',true);
console.log(elem.prop("checked")); //true
console.log(elem[0]); //<input type="checkbox" name="checkbox1" value="12345">
The DOM does not magically add the property as an attribute when you inspect it. If you want the HTML to update, you would have to add an attribute
var elem = $('<input type="checkbox" name="checkbox1" value="54321">').attr("checked","checked");
console.log(elem.prop("checked")); //true
console.log(elem[0]); //<input type="checkbox" name="checkbox1" value="12345" checked="checked">
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments