Keep radio button form from submitting when nothing is checked jquery

微笑、不失礼 提交于 2019-12-11 10:07:56

问题


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>

回答1:


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().

Try this:

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



来源:https://stackoverflow.com/questions/22754026/keep-radio-button-form-from-submitting-when-nothing-is-checked-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!