保持单选按钮的形式从什么时候检查提交的jQuery(Keep radio button form f

2019-10-19 17:43发布

我怎么去有没事的时候选中此不提交,但随后有当一个人被选中提交? 目前,它提交两种方式。 我缺少的是在这里吗? 它抛出了我希望它没事的时候被检查到的错误“请检查上面的选项之一”,但然后进入登陆页面。 感谢您的任何帮助!

$(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>

Answer 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



文章来源: Keep radio button form from submitting when nothing is checked jquery