我有一组单选按钮,我想取消后AJAX表单提交使用jQuery。我有以下功能:

function clearForm(){
  $('#frm input[type="text"]').each(function(){
      $(this).val("");  
  });
  $('#frm input[type="radio":checked]').each(function(){
      $(this).checked = false;  
  });
 }

在这个函数的帮助下,我可以清除文本框中的值,但我不能清除单选按钮的值。

顺便说一下,我还尝试了$(this).val("");但这并没有起作用。


当前回答

谢谢帕特里克,你让我今天很开心!你必须使用鼠标下键。不过,我已经改进了代码,以便您可以处理一组单选按钮。

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());

其他回答

你可以使用JQuery来取消选中单选按钮

$('input:radio[name="IntroducerType"]').removeAttr('checked');
                $('input:radio[name="IntroducerType"]').prop('checked', false);

使用这个

$("input[name='nameOfYourRadioButton']").attr("checked", false);
function setRadio(obj) 
{
    if($("input[name='r_"+obj.value+"']").val() == 0 ){
      obj.checked = true
     $("input[name='r_"+obj.value+"']").val(1);
    }else{
      obj.checked = false;
      $("input[name='r_"+obj.value+"']").val(0);
    }

}

<input type="radio" id="planoT" name="planoT[{ID_PLANO}]" value="{ID_PLANO}" onclick="setRadio(this)" > <input type="hidden" id="r_{ID_PLANO}" name="r_{ID_PLANO}" value="0" >

:D

$('#frm input[type="radio":checked]').each(function(){
   $(this).checked = false;  
  });

这几乎是很好的,但你错过了[0]

正确->> $(this)[0]。Checked = false;

(纯js)

this.checked = false;

或(jQuery)

$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);

请参阅jQuery prop()帮助页面,了解attr()和prop()之间的区别,以及为什么prop()现在更可取。 prop()是2011年5月在jQuery 1.6中引入的。