当没有检查jquery时,不要提交单选按钮表单

问题描述:

如何在未检查任何内容的情况下不提交此文件,而在检查任何内容的情况下将其提交呢?它当前以任何一种方式提交.我在这里想念什么?当未选中任何内容时,抛出我想要的错误",请检查以上选项之一",然后转到登录页面.感谢您的任何帮助!

How do I go about having this not submit when nothing is checked, but then having it submit when one is checked? It currently submits either way. What am I missing here? It throws up the error I want it to when nothing is checked "Please check one of the options above" but then goes to the landing page. Thank you for any help!

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

如果要防止默认行为,请使用

When you want to prevent the default behaviour use .preventDefault(). For example in your case a form submit event, if you want to validate inputs before form post and stop submitting form if any errors, use 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