【问题标题】:Keep radio button form from submitting when nothing is checked jquery当没有检查jquery时,保持单选按钮表单不提交
【发布时间】:2014-05-10 08:19:00
【问题描述】:

如何在未检查任何内容时不提交,但在检查时提交?它目前以任何一种方式提交。我在这里想念什么?当没有选中“请检查上述选项之一”时,它会抛出我想要的错误,然后进入登录页面。感谢您的任何帮助!

$(document).ready(function () {
    $("#submitbutton").click(function () {
        var none_answered = true;
        $("input:radio").each(function () {
            var name = $(this).attr("name");
            if ($("input:radio[name]:checked").length == 0) {
                none_answered = false;
            }
        });
        if (none_answered == false) {
            $('#texthere').html("Please check one of the options above");
        }
    })  
});

<style type="text/css">


#texthere
{
    color:red;
}

</style>

<body>
    <form>  
        <input type="radio" name="refer" value="Strategic Communication" >Strategic Communication</br>
        <input type="radio" name="refer" value="Journalism" >Journalism</br>
        <input type="radio" name="refer" value="Communication Studies" >Communication Studies</br>
        <div id="texthere"></div>

        <input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
    </form>     
</body>

【问题讨论】:

    标签: jquery forms button submit radio


    【解决方案1】:

    如果您想阻止默认行为,请使用.preventDefault()。例如,在您的情况下是表单提交事件,如果您想在表单发布之前验证输入并在出现任何错误时停止提交表单,请使用 event.preventDefault()。

    试试这个:

    $(document).ready(function () {
        $("#submitbutton").click(function (e) {
            var none_answered = true;
            $("input:radio").each(function () {
                var name = $(this).attr("name");
                if ($("input:radio[name]:checked").length == 0) {
                    e.preventDefault();
                    none_answered = false;
                }
            });
            if (none_answered == false) {
                $('#texthere').html("Please check one of the options above");
            }
        })  
    });
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-13
      • 2013-10-06
      • 2023-03-29
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多