开发者

Uncheck radio buttons using jQuery general selectors

I have the following form (it is dynamically generated and I have a few copies of it named form-0 to form-3)

<for开发者_如何学Pythonm 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 of attr() :

$('form[id^="form-"]').find("input:radio:checked").prop('checked',false);

// OR (not recommended)

$('form[id^="form-"]').find("input:radio:checked").removeProp('checked');

However, it is not advised to use the removeProp variant, according to the documentation :

Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

( thanks @noah1989 for pointing this out )

attr() retrieves the value that have been set in the source code, and prop() retrieves the current, dynamically set value of the attribute.

You can see a jsFiddle example here


You should be able to uncheck using

$('input[name=foo]').attr('checked', false);

My initial guess is that you get a collection of radio buttons from your find. Thaus you should use .each() to loop them and set the checked attribute to false on each individual one.

Something like this (not testet, so might be a syntax error)

$('form[id^="form-"]').find("input:radio:checked").each(
  function() {
    $(this).attr('checked', false);
  }
);


<input type="radio" id="ra1" onclick="change('ra1')" onmousedown="getvalue('ra1')"/>
function getvalue(id){
    ischecked = document.getElementById(id).checked;
}
function change(id){
    if(ischecked == false)
        document.getElementById(id).checked=true;
    else
        document.getElementById(id).checked=false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜