如何在验证期间根据复选框更改变量

发布于 2024-08-20 11:47:47 字数 413 浏览 3 评论 0原文

我已经使用以下代码成功地使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何必那么矫情 2024-08-27 11:47:47

试试这个:

var mySecondVar = $("input[name='mySecondVar']:checked").length ? "Yes" : "No";

Try this:

var mySecondVar = $("input[name='mySecondVar']:checked").length ? "Yes" : "No";
活雷疯 2024-08-27 11:47:47

选择器的“:checked”部分只是告诉 jQuery 仅选择已检查的项目。 jQuery 选择器总是返回结果(jQuery 对象),因此简单地将选择器放在 if 子句中是不够的。您想查看结果是否实际包含任何元素,因此 $("input[name='mySecondVar']:checked").length 将适用于您的条件子句(因为 Javascript 将 0 解释为“错误的”)。

另一种方法是

if ($("input[name='mySecondVar']")[0].checked) {
     var mySecondVar = "Yes";
    }
    else {
     var mySecondVar = "No";
    }

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

if ($("input[name='mySecondVar']")[0].checked) {
     var mySecondVar = "Yes";
    }
    else {
     var mySecondVar = "No";
    }
蓝眼睛不忧郁 2024-08-27 11:47:47

您可以根据条件设置 Java 脚本变量。

if($("input[name='testVar']:checked").length)
  set variable
else
  set variable

You can set your java script variable's based on condition.

if($("input[name='testVar']:checked").length)
  set variable
else
  set variable
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文