21

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.

turbo2oh
  • 2,849
  • 6
  • 34
  • 46
  • Include for true, leave out for false `` `` –  Jul 01 '14 at 15:55
  • Your example works for me http://jsfiddle.net/j08691/qSSa8/. Are you just looking at the console output, or the actual DOM rendering? Have you tried `.removeAttr()`? – j08691 Jul 01 '14 at 15:55
  • if you want it unchecked then :``​``, if checked then:``​`` – Ehsan Sajjad Jul 01 '14 at 15:56
  • 1
    Check this [prop() vs attr()](http://stackoverflow.com/q/5874652/3639582) – Shaunak D Jul 01 '14 at 15:56
  • 1
    possible duplicate of [What is the syntax for boolean attributes, e.g. a checked checkbox, in HTML?](http://stackoverflow.com/questions/2874949/what-is-the-syntax-for-boolean-attributes-e-g-a-checked-checkbox-in-html) – drew_w Jul 01 '14 at 15:56
  • 3
    `prop()` does not update the HTML, just the DOM. If you're going to inspect the HTML afterwards use `attr()` or `removeAttr()` –  Jul 01 '14 at 15:57

3 Answers3

38

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.

user1094553
  • 786
  • 5
  • 15
0

$(document).ready(function () { $(e).prop("checked", false);}

// "e" refers to button element

gesown
  • 21
  • 1
-1

How to Uncheck in this case, example my code is: (see below)

if(previousHighlightedCheckbox!=null) {
    console.log(sent.id, previousHighlightedCheckbox); // current checkbox and previous check box values are different.
    document.getElementById(previousHighlightedCheckbox).checked = false; // still this does not uncheck previous one
  } 
Shahnawaz Kadari
  • 1,423
  • 1
  • 12
  • 20