JacobIRR
JacobIRR

Reputation: 8946

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.

Upvotes: 0

Views: 179

Answers (3)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

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.

Upvotes: 0

nivanmorgan
nivanmorgan

Reputation: 149

You can use .prop or .attr for the checkbox

<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>

Upvotes: 3

Intervalia
Intervalia

Reputation: 10935

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.

Upvotes: 3

Related Questions