I have the following form (it is dynamically generated and I have a few copies of it named form-0 to form-3)
<form id="form-0" name="0">
<b>what is bla?</b><br>
<div class="ansN" id="ans0"><input type="radio" name="answerN" value="0"> aaa </div>
<div class="ansN" id="ans1"><input type="radio" name="answerN" value="1"> bbb </div>
<div class="ansN" id="ans2"><input type="radio" name="answerN" value="2"> ccc </div>
<div class="ansN" id="ans3"><input type="radio" name="answerN" value="3"> ddd </div>
<input type="submit" value="Submit your answer">
</form>
(ignore the divs, they are used for some other purpose)
Itry to create an uncheck function so that will work on all the radio-buttons on the page,
so I played with the console and tried to deselect them using this:
$('form[id^="form-"]').find("input:radio:checked").attr('checked', false);
$('form[id^="form-"]').find("input:radio:checked").removeAttr("checked");
So the selector did find all the checked buttons, but it didn’t uncheck them, why?
when I use direct JS call: document.forms[0].answerN[3].checked = false it works fine,
so I can use it inside a loop but I try to avoid loops here. Is there a better way?
My goal is to have an uncheck function, so the second click on the radio button itself will uncheck it
If you are using jQuery 1.6, you could use
prop()instead ofattr():However, it is not advised to use the
removePropvariant, according to the documentation :( thanks @noah1989 for pointing this out )
attr()retrieves the value that have been set in the source code, andprop()retrieves the current, dynamically set value of the attribute.You can see a jsFiddle example here