【问题标题】:Update value based on :checked status根据 :checked 状态更新值
【发布时间】:2010-07-05 13:27:48
【问题描述】:
<input type="checkbox" name="feature1" value="0" />

如果选中,则 value="1"; 其他值=“0”;

if ( $('input[name=feature1]').is(':checked') ) {
  $('input[name=feature1]').val('1');
}

我认为上面的 jQuery 可能工作,但它的一次性检查,我如何使它每次单击/选中复选框时,值变为 1,否则为 0?

非常感谢

【问题讨论】:

    标签: jquery forms checkbox toggle


    【解决方案1】:
    $('input[name=feature1]').click(function(){
        if ($(this).is(':checked') ) {
          $(this).val('1');
        } else {
          $(this).val('0');
        }
    });
    

    $('input[name=feature1]').click(function(){
        if (this.checked) {
          $(this).val('1');
        } else {
          $(this).val('0');
        }
    });
    

    好多了

    $('input[name=feature1]').click(function(){
          $(this).val(this.checked ? 1:0);
    });
    

    正如我认为还有更好的方法..

    $('input[name=feature1]').click(function(){
          this.value = this.checked ? 1:0;      
    });​
    

    【讨论】:

    • 是的,但这是一次性检查,而不是切换。没有?
    • 太棒了,它就像一个魅力。只是想知道它是否适用于多个元素 $('one, two, three').. ?
    【解决方案2】:

    我会给输入一个 ID,只是为了让你的 jQuery 更容易编写——为了回答这个问题,我会假装我们重复了这个名字。

    jQuery("#feature1").click(function() {
       if (this.checked) {
          jQuery(this).val(1);
       } else {
          jQuery(this).val(0);
       }
    });
    

    【讨论】:

    • 不过有一个问题 - 为什么需要为其设置一个值?如果您使用的是 PHP,那么只有在选中复选框时才会提交该值,您只需检查它 isset() 即可获取值..
    猜你喜欢
    • 2021-12-09
    • 2019-10-23
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多