通过 jQuery 检索并显示单选选项的值

发布于 2024-07-27 13:17:10 字数 513 浏览 1 评论 0原文

我试图让警报框显示我选择的单选选项的值。 HTML:

<input type="radio" name="sex" value="Male" /> Male<br />
<input type="radio" name="sex" value="Female" /> Female

当我选择其中之一并设置警报框来显示我选择的内容(作为测试)时,它不起作用。 我知道其他人告诉我们要这样设置:

var sex = $('input[name=sex]:checked').val();

但是,当我这么说时,整个脚本就会自行崩溃。 什么都不起作用。 我之前的脚本看起来像:

var sex = $('input[name=sex]:checked');

并且脚本仍然有效,但警报仅显示“[object Object]”。 我究竟做错了什么?

I'm trying to have an alert box show the value of the radio option I have selected.
HTML:

<input type="radio" name="sex" value="Male" /> Male<br />
<input type="radio" name="sex" value="Female" /> Female

When I choose one of those and set up and alert box to show me what i choose (as a test), it doesn't work.
I know that other people are telling to set this up like:

var sex = $('input[name=sex]:checked').val();

However, when i put that, the entire script just craps on itself. Nothing works.
The script I have before looked like:

var sex = $('input[name=sex]:checked');

and with that the script still worked, but the alert only showed "[object Object]".
What am i doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

通常单选按钮的值是开/关。 您可能想尝试使用:

 var sex = $('input[name=sex]:checked').attr('value');

另一方面,我没有看到您的代码有任何会导致其失败的内容(除非 jQuery 中存在无法处理您的自定义值的错误)。

您是否使用 Firefox/Firebug 查看控制台错误是什么? 这可能是完全不相关的事情。

Usually the value of a radio button is on/off. You might want to try using:

 var sex = $('input[name=sex]:checked').attr('value');

On the other hand, I don't see anything about your code that should cause it to fail (unless there's a bug in jQuery that can't handle your custom values).

Have you used Firefox/Firebug to see what the console error is? It may be something completely unrelated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文