0

我有两个像这样的单选按钮

<input type="radio" name="rush" value="yes" />
<input type="radio" name="rush" value="no" checked="checked" />

我想要做的是单击表单提交按钮时,检查是否选择了“是”。

如果是,显示一个 javascript 确认对话框

我已经走了这么远,但被卡住了,任何帮助将不胜感激。

$("form.shipping").submit(function() {

    if($("input[name='rush']".attr("value") === "yes")
    {
        if (confirm("Rush orders are subject to an upcharge. (Just wanted to make sure you read the note). Is this ok?"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

});
4

3 回答 3

5

您正在将某些内容绑定到click按钮的事件。您可能希望将其绑定到submit表单的事件。除此之外,您input.sumbit-button在选择器中拼写错误。

编辑是您想要的工作版本。你的错误是:

  • 您可能没有将代码包装在document.ready. 如果您的脚本包含在页面顶部,这一点很重要,因为您编写的任何未包含在此事件中的内容都将在创建 DOM 元素之前执行。因此,您将事件绑定到任何内容。该document.ready事件通过在 DOM 完全加载后立即触发来处理这一点。
  • )你之前有一个缺失的结束.attr。你可能应该研究像FireBug这样的工具来调试你的 javascript,因为用它来找到这些东西是微不足道的。
  • 您正在检查单选按钮的值,但它始终评估为 true,因为您需要将其过滤掉以仅获取:checked一个。

所以,工作代码:

$(document).ready(function() {
    $("form.shipping").submit(function() {
        if($("input[name='rush']").is(":checked")) {
            return confirm("Rush orders are subject to an upcharge.
            (Just wanted to make sure you read the note). Is this ok?");
        }
    });
});
于 2009-04-09T20:14:47.490 回答
0

它会在多个浏览器中失败吗?我在 IE7 中看到过一些奇怪的错误报告,其中确认()没有在 onclick 或 onsubmit 事件处理程序中执行。

于 2009-04-09T20:27:10.860 回答
0

你的选择器 "input[name='rush']" 将返回两个输入,你需要 "input[name='rush']:checked" 正如 Paolo Bergantino 建议的那样

于 2009-04-09T20:42:13.540 回答