Neir0
Neir0

Reputation: 13377

Check and uncheck checkboxes

How to right check and uncheck checkboxes? I have many troubles with it.

Here is my code http://jsfiddle.net/N5Swt/ :

<input type="checkbox" id="checkbox1" /> <span> Check me! </span>

// test1
/*$('#checkbox1').attr('checked','true');
$('#checkbox1').attr('checked','false');*/ // This line doesnt work

// test2
$('#checkbox1').attr('checked','true');
$('#checkbox1').removeAttr('checked');
$('#checkbox1').attr('checked','true'); //This line doesnt work

It doesnt work. Why?

Upvotes: 1

Views: 4083

Answers (5)

dsgriffin
dsgriffin

Reputation: 68626

jQuery:

You can use jQuery's prop() instead:

$('#checkbox1').prop('checked', true);

to uncheck you'd just use:

$('#checkbox1').prop('checked', false);

jsFiddle here.


Pure Javascript:

In pure Javascript you could use the .checked property:

document.getElementById('checkbox1').checked = true;

to uncheck you'd just use:

document.getElementById('checkbox1').checked = false;

jsFiddle here.

Upvotes: 7

KooiInc
KooiInc

Reputation: 122986

You can also address the element property directly:

document.querySelector('#checkbox1').checked = true;
// or
$('#checkbox1')[0].checked = true;

JsFiddle demo

Upvotes: 1

Romko
Romko

Reputation: 1798

better use native javascript property its clear and always works

$('#checkbox1')[0].checked = true;

Upvotes: 1

Codesen
Codesen

Reputation: 7842

This is working...

$('#checkbox1').attr('checked',true);
$('#checkbox1').attr('checked',false);

Upvotes: 0

epascarello
epascarello

Reputation: 207557

You should be using prop() to set the checkbox value and not attr.

And you are setting a Boolean so you should not be using a string to set the property's value.

$('#checkbox1').prop('checked',false);

Upvotes: 1

Related Questions