当没有检查jquery时,不要提交单选按钮表单 [英] Keep radio button form from submitting when nothing is checked jquery

查看:87
本文介绍了当没有检查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

这篇关于当没有检查jquery时,不要提交单选按钮表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆