如何在验证期间根据复选框更改变量
我已经使用以下代码成功地使用 jQuery 1.4 从单选按钮组中提取了选中的值:
var myFirstVar = $("input[name='myFirstVar']:checked").val();
我如何更改此代码以查明是否选中了复选框,并根据是否选中了 var 的值是否被检查。
我尝试了很多方法,但这里有一个我认为可行的示例:
if ($("input[name='mySecondVar']:checked")) {
var mySecondVar = "Yes";
}
else {
var mySecondVar = "No";
}
任何有关简单更改值(无论是否选中该框)的见解都会很棒。
I've successfully pulled the checked value from a radio button group with jQuery 1.4 using the following code:
var myFirstVar = $("input[name='myFirstVar']:checked").val();
How would I alter this code to find out whether a check-box was checked, and to change the value of the var based on whether it is checked or not.
I tried many things, but here is an example of what I thought would work:
if ($("input[name='mySecondVar']:checked")) {
var mySecondVar = "Yes";
}
else {
var mySecondVar = "No";
}
Any insight on simply changing the value whether the box is checked or not would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
选择器的“:checked”部分只是告诉 jQuery 仅选择已检查的项目。 jQuery 选择器总是返回结果(jQuery 对象),因此简单地将选择器放在 if 子句中是不够的。您想查看结果是否实际包含任何元素,因此
$("input[name='mySecondVar']:checked").length
将适用于您的条件子句(因为 Javascript 将 0 解释为“错误的”)。另一种方法是
The ":checked" part of the selector is just telling jQuery to only select items that are checked. jQuery selectors always return a result (the jQuery object), so simply putting the selector in the if clause isn't sufficient. You want to see whether the result actually included any elements, so
$("input[name='mySecondVar']:checked").length
will work for your conditional clause (since Javascript interprets 0 as "false").Another approach would be
您可以根据条件设置 Java 脚本变量。
You can set your java script variable's based on condition.