Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checkbox set to checked = false not working

I'm generating an HTML input with checked="false", however the checkbox is showing up checked.

I did the following in the javascript console and can't quite figure out whats going on. The resulting HTML after using .prop() to set the value to false looks the same except now the checkbox is not checked on the form.

> $(':input[checked]').prop('checked');
< true
> $(':input[checked]')
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
> $(':input[checked]').prop('checked',false);
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]

I'm under the impression that I should just be setting checked="checked" OR not including the checked property at all if its false is that best practice? Either way I'd like to know what's going on in the above code.

like image 894
turbo2oh Avatar asked Jul 01 '14 15:07

turbo2oh


People also ask

How do you set a checkbox to false value?

val( checkbox[0]. checked ? "true" : "false" ); This will set the value of the checkbox to "true" or "false" ( value property is a string) , depending whether it's unchecked or checked .

How check checkbox is true or false in JavaScript?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Does checkbox return true or false?

The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


1 Answers

Don't put checked="false"

You only put checked="checked" for valid XHTML, otherwise you'd do

<input type="checkbox" checked>

The browser doesn't care what value is assigned to checked attribute, as soon as it sees checked in the checkbox input tag, it's flagged as checked.

like image 133
user1094553 Avatar answered Nov 04 '22 02:11

user1094553