Search code examples
jqueryformsradio-button

Keep radio button form from submitting when nothing is checked 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>

Solution

  • 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