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

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

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

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


当前回答

重写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 );

其他回答

电台及电台组:

$(document).ready(function() {
    $(document).find("input:checked[type='radio']").addClass('bounce');   
    $("input[type='radio']").click(function() {
        $(this).prop('checked', false);
        $(this).toggleClass('bounce');

        if( $(this).hasClass('bounce') ) {
            $(this).prop('checked', true);
            $(document).find("input:not(:checked)[type='radio']").removeClass('bounce');
        }
    });
});

下面是jQuery的代码:

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

对于javascript:

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

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

重写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[id^="rad"]').dblclick(function(){
    var nombre = $(this).attr('id');
    var checked =  $(this).is(":checked") ;
    if(checked){
        $("input[id="+nombre+"]:radio").prop( "checked", false );
    }
});

每次双击选中的单选,选中的单选就变为false

我的无线电以id=radxxxxxxxx开头,因为我使用这个id选择器。

(纯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中引入的。