Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I uncheck a checked checkbox programmatically?

Say I have the following sample:

<input name="Opt1" id="Opt1" type="checkbox" value="1" alt="1948" title="RQlevel1" src="2" checked="checked" onclick="levels();"/>  <label style="cursor:pointer" for="OptID12851948">PADI Advanced Open Water</label>

<input name="Opt2" id="Opt2" type="checkbox" value="2" alt="1953" title="RQlevel2" src=""  onclick="levels();"/>  <label style="cursor:pointer" for="OptID19521953">PADI Rescue</label>

<input name="Opt3" id="Opt3" type="checkbox" value="3" alt="1957" title="RQlevel2" src=""  onclick="levels();"/>  <label style="cursor:pointer" for="OptID19521953">PADI Rescue2</label>

If I click PADI Advanced Open Water checkbox, which will then call the levels() JavaScript function, how can I programmatically uncheck this checked checkbox using jQuery?

I have tried the following but doesn't work:

if ($("input[value='1']:checked").attr("checked")){
    $("input[value='1']:checked").attr(“checked”, false);
}   
like image 784
tonyf Avatar asked Dec 12 '22 07:12

tonyf


2 Answers

Use removeAttr:

$("input[value='1']:checked").removeAttr('checked');

Or with recent versions of jQuery, you can use prop:

$("input[value='1']:checked").prop('checked', false);
like image 55
mu is too short Avatar answered Dec 22 '22 00:12

mu is too short


If your using jQuery 1.6 and up you should really use .prop() for this

In addition your selector already determines that the input is checked. There is no need to duplicate that by checking the attribute or propery.

if ($("input[value='1']:checked").length) { 
    $("input[value='1']:checked").prop("checked", false); 
}    

However if you are using a version of jQuery lower than 1.6 this will work by using removeAttr().

if ($("input[value='1']:checked").length) { 
    $("input[value='1']:checked").removeAttr("checked"); 
}    
like image 35
John Hartsock Avatar answered Dec 22 '22 01:12

John Hartsock