【问题标题】:Form checkboxes/radios need class change表单复选框/收音机需要更改类
【发布时间】:2011-06-22 01:00:16
【问题描述】:

我正在做一个表单,其中用户有一个选项列表。一些单选按钮,一些复选框。用户可能是一厢情愿的,会改变主意。我需要更改输入和类中的检查值,因此我可以通过表单提交来定位这些值。这需要在用户单击提交之前发生。这是我到目前为止所拥有的,它更改了“已检查”属性和类,但是一旦不再选择按钮,它们就不会变回来。救命!

$("input:checkbox, input:radio").change(function() {
if ($("input:checked")) {
    $(this).attr("checked",true);
    $(this).addClass("checked");
} else {
    $(this).attr("checked",false);
    $(this).removeClass("checked");
}
});

更新:仍然没有。我已将其缩减为以下内容,但它仍然没有删除更改类。

    $("input:checkbox, input:radio").change(function ()
   {
       if (this.checked)
      {
         $(this).addClass("checked");
      }
      else
       {
         $(this).removeClass("checked");
       }
   });

【问题讨论】:

    标签: jquery attributes checkbox radio-button


    【解决方案1】:

    你可以试试:

    if ($(this).is(":checked")) { $(this).attr("checked",true); $(this).addClass("checked"); } 别的 { $(this).removeAttr("checked"); $(this).removeClass("checked"); }

    【讨论】:

      【解决方案2】:

      您是否尝试过使用 if($(this).attr('checked')) 而不是 if ($("input:checked"))attr方法根据你使用的参数是getter或者setter方法。

      【讨论】:

        【解决方案3】:

        使用prop():

        $(this).prop("checked",true);
        

        还有:

        $(this).prop("checked",false);
        

        请参阅此问题:.prop() vs .attr() 了解原因

        一般还要更改您的代码,因为如果您的页面上有 any 复选框,则在您版本中声明语句的第一部分始终为真:

        $("input:checkbox, input:radio").change(function ()
        {
            if (this.checked)
            {
                $(this).prop("checked", true);
                //also since it is a change event you probably 
                //don't need these prop() lines
                $(this).addClass("checked");
            }
            else
            {
                $(this).prop("checked", false);
                $(this).removeClass("checked");
            }
        });
        

        更新

        您的更新似乎对我有用:http://jsfiddle.net/maniator/r7Yf6/

        【讨论】:

        • 干杯@Neal,他试图编辑你的答案,所以我拒绝了它并发布了评论。 (afaik 编辑帖子不会发送任何通知吗?)
        • @shadow,不相信(等待 OP 试图编辑我的答案,为什么?)
        • @Shadow -- OP 在我的答案中添加了什么?
        • @Neal 与他在自己的问题中添加的内容完全相同,否则我会将他所说的话添加到我自己的评论中。
        猜你喜欢
        • 1970-01-01
        • 2013-11-14
        • 2012-10-16
        • 2023-03-17
        • 1970-01-01
        • 2012-02-13
        • 2018-02-05
        • 2010-11-19
        • 2017-08-14
        相关资源
        最近更新 更多