Why is a newly created checkbox checked when I set checked to false?
When I put this code in my console, I end up with a checked box in my web page:
$('body').append($('<input/>', {
type: 'checkbox',
value: "foo",
checked: false
}));
When I remove the checked attr altogether, the box is not checked:
$('body').append($('<input/>', {
type: 'checkbox',
value: "foo",
}));
...but I need a dynamic set of checkboxes to be generated, some checked and some not. What attr/value creates the correct "unchecked" state?
UPDATE:
I am using the latest Chrome. jQuery version 3.2.1 The code works as expected in this fiddle: https://jsfiddle.net/mmvunhL0/ But not on my website... I'm wondering if there is a global setting or something touching the checkbox behavior.
您可以使用.prop或.attr作为复选框
<div id="body">
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script>
var value = true;
$('#body').append($('<input/>', {
type: 'checkbox',
value: "foo",
}).prop('checked', value) ) ;
value = false;
$('#body').append($('<input/>', {
type: 'checkbox',
value: "foo",
}).prop('checked', value) );
</script>
When used with the checkbox, the attribute checked
is a boolean attribute.
If it exists at all then it is true.
<input type="checkbox" checked />
is the same as
<input type="checkbox" checked="false" />
and
<input type="checkbox" checked="checked" />
The only way to not have it checked is by not having the checked
attribute at all.
You're getting unchecked on both of your code. Because, by default the checkbox is unchecked and if you want it to be checked explicitly, then define checked to true.
$('body').append($('<input/>', {
type: 'checkbox',
value: "foo",
checked: true
}));
If you want it randomly, then you can use Math:
$('body').append($('<input/>', {
type: 'checkbox',
value: "foo",
checked: Boolean(Math.round(Math.random()))
}));
Boolean is necessary here. It's because the property value strictly look for true of false value but not truthy or falsy value.
链接地址: http://www.djcxy.com/p/56030.html