【问题标题】:Changing the value of the checkboxes via jQuery通过 jQuery 更改复选框的值
【发布时间】:2011-08-17 20:33:38
【问题描述】:

我的表单中有几个复选框,当复选框被选中时,我需要更改它们的值。

例如这是复选框之一:

<input type="checkbox" name="drink" value=""/>

我知道.val() 可以更改它,但我无法使用if 语句来做到这一点。

提前感谢您的回答。

【问题讨论】:

  • 选中哪个复选框会更改其他哪个复选框?你的问题缺乏细节

标签: php javascript jquery checkbox


【解决方案1】:

你所寻求的其实是很没有意义的。看,当提交表单时,只有 checked 复选框实际发送值,因此更改值是没有意义的,尤其是对于未选中的复选框。


更好的解决方案

您应该给它“检查”值,并保持这种状态,即使不更改值也将导致它正确提交。

【讨论】:

  • 我没有解释我的目的,我只是问了我缺少的部分来完成我的项目。其他答案解决了我的问题。谢谢您的回答。
【解决方案2】:

您可以在复选框上添加点击事件监听器:

$('input[name="drink"]').click(function() { // when click on it
    if ($(this).attr('checked')) {          // if the checkbox is checked
       $(this).val("value #1");             // change the value
    } else {                                // otherwise if is unchecked
       $(this).val("value #2");             // change the value
    }
});

【讨论】:

  • 最好将侦听器附加到change 事件。复选框的状态也可以通过键盘更改,但您的代码不会捕捉到这一点。
【解决方案3】:
// attach an onchange handler to all checkboxes on the page
$("input[type='checkbox']").change(function() {

    // or if($(this).prop("checked")) {
    if(this.checked) {
        $(this).val("value for checked");
    } else {
        $(this).val("value for unchecked");
    }
});
  • onchange 事件是您应该对复选框感兴趣的事件,因为它会在您更改复选框的选中状态时触发。
  • checked 属性确定复选框是否已被选中。
  • .val() 方法允许您方便地读取/写入元素值。

【讨论】:

  • 谢谢卡里姆,你的回答救了我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多