如果使用jquery选中单选按钮,如何执行javascript确认对话框

mjr*_*mjr 0 validation jquery webforms radio-button

我有两个单选按钮

<input type="radio" name="rush" value="yes" />
<input type="radio" name="rush" value="no" checked="checked" />
Run Code Online (Sandbox Code Playgroud)

我想要做的是当单击表单提交按钮时,检查是否选择了"是".

如果是,则显示一个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;
        }
    }

});
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 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?");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)