如何使用JQuery更改onClick复选框的值? [英] How to change the value of a check box onClick using JQuery?

查看:110
本文介绍了如何使用JQuery更改onClick复选框的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我试图在点击它时更改以下复选框的值。在下面的代码中,我尝试将复选框的值更改为1,并在取消选中时将值更改为0。但它只需要错误的条件,当取消选中复选框时,值会更改为0,但是当选中时它不会更改为1.有任何建议如何解决这个问题吗?

Here I am trying to change the value of the following check box while clicking on it. In the code below I tried to change the value of the checkbox to 1 and change the value to 0 when unchecked. But it takes only the false condition, when the checkbox is unchecked the value changes to 0 but when checked its not changing to 1. Any suggestions how to fix this out ?

<input type="checkbox" id="read" name="permission[]" onClick="($(this).checked)?$(this).attr('value',1):$(this).attr('value',0)"/>


推荐答案

我真的不明白为什么你我希望这样做(当取消选中时,复选框的值不会被提交)。

已检查 DOM元素上的属性将始终告诉您是否已选中它。所以你可以得到 this.checked (Javascript DOM)或 $(this).prop('checked') (jQuery wrapper)。

The checked property on the DOM element will always tell you whether it is checked or not. So you can either get this.checked (Javascript DOM) or $(this).prop('checked') (jQuery wrapper).

如果你真的需要,你应该这样做:

If you really need to, you should do this:

onclick="$(this).attr('value', this.checked ? 1 : 0)"

甚至

onclick="$(this).val(this.checked ? 1 : 0)"

甚至更好,不要使用内联事件处理程序(比如 onclick ),但是使用jQuery的事件处理包装器( .on('click') 旧版本中的 .click()

or even better, don't use inline event handlers (like onclick), but use jQuery's event handling wrappers (.on('click') or .click() in older versions).

使用jQuery事件处理的jsFiddle演示

您使用的是 $(this).checked 获取复选框的状态。 jQuery对象(由 $ 函数返回的对象)没有已选中属性,因此它将是未定义。在Javascript中, undefined 是一个 falsy 值,这就是为什么你的复选框的值总是 0

You are using $(this).checked to get the state of your checkbox. The jQuery object (the one that's returned by the $ function) does not have a checked property, so it will be undefined. In Javascript, undefined is a falsy value, that's why your checkbox's value is always 0.

这篇关于如何使用JQuery更改onClick复选框的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆