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

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

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

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


当前回答

Try

$(this).removeAttr('checked')

因为很多浏览器会把'checked=anything'解释为真。这将完全删除checked属性。

希望这能有所帮助。

其他回答

试试这个,这个会有效果的:

        $(document).ready(function() {
           $("input[type='radio']").mousedown(function(e) {
                if ($(this).attr("checked") == true) {
                   setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);}
                else {
                    return true
                }
            });
        });

使用这个

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

重写Igor的代码为插件。

Use:

$('input[type=radio]').uncheckableRadio();

插件:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );

你也可以只使用复选框来模拟单选按钮的行为:

<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />

然后,你可以使用这段简单的代码为你工作:

$(".fakeRadio").click(function(){
    $(".fakeRadio").prop( "checked", false );
    $(this).prop( "checked", true );
});

它工作得很好,你可以更好地控制每个按钮的行为。

你可以自己试试:http://jsfiddle.net/almircampos/n1zvrs0c/

这个fork还可以让你取消所有在注释中请求的选择: http://jsfiddle.net/5ry8n4f4/

下面是jQuery的代码:

jQuery("input:radio").removeAttr("checked");

对于javascript:

$("input:radio").removeAttr("checked");

没有必要在foreach循环,.each()函数或任何东西