代码之家  ›  专栏  ›  技术社区  ›  Harish Kumar

多无线电组验证

  •  0
  • Harish Kumar  · 技术社区  · 11 年前

    我正在尝试验证多个单选按钮组,验证后应提交表单。验证工作正常,但正在提交,请帮助。

    <form action="" method="post" name="surveyForm" id="surveyForm" onSubmit="return checkdata();">
        <div>
            <input class="attrInputs" type="radio" name="chest" value="A">
            <input class="attrInputs" type="radio" name="chest" value="B">
            <input class="attrInputs" type="radio" name="chest" value="C">
        </div>
        <br />
        <div>
            <input class="attrInputs" type="radio" name="chest1" value="A">
            <input class="attrInputs" type="radio" name="chest1" value="B">
            <input class="attrInputs" type="radio" name="chest1" value="C">
        </div>
        <br />
        <input type="submit" value="click" onclick="return checkdata()" />
    </form>
    <script>
        function checkdata() {
            return checkdata1_2();
            return checkdata1_1();
        }
        function heckdata1_2() {
            if ($('input[name=chest]:checked').length <= 0) {
                alert("No radio checked");
                return false;
            }
        }
    </script>
    <script>
        function checkdata1_1() {
            if ($('input[name=chest1]:checked').length <= 0) {
                alert("No radio checked");
                return false;
            }
        }
    </script>
    
    2 回复  |  直到 11 年前
        1
  •  1
  •   Sachin    11 年前

    问题不止一个 return 陈述它将从第一个返回 回来 语句,不会检查下一行代码。我认为,当你可以在一个函数中完成所有这些时,甚至不需要两个函数。

    这是一个简单的方法:

    <form action="" method="post" name="surveyForm" id="surveyForm" onsubmit="return checkdata();">
    <div>
        <input class="attrInputs" type="radio" name="chest" value="A">
        <input class="attrInputs" type="radio" name="chest" value="B"><input class="attrInputs"
            type="radio" name="chest" value="C"></div>
    <br />
    <div>
        <input class="attrInputs" type="radio" name="chest1" value="A"><input class="attrInputs"
            type="radio" name="chest1" value="B">
        <input class="attrInputs" type="radio" name="chest1" value="C"></div>
    <br />
    <input type="submit" value="click" onclick="return checkdata()" /></form>
    <script>
        function checkdata() {
            if ($('input[name=chest]:checked').length <= 0) {
                alert("No radio checked");
                return false;
            }
            if ($('input[name=chest1]:checked').length <= 0) {
                alert("No radio checked");
                return false;
            }
        }
    </script>
    

    检查 Fiddle

        2
  •  0
  •   lshettyl    11 年前

    或者只需使用以下函数。这将检查是否至少选中了2个单选按钮,即每组1个。因此,只有在每个组中至少选中一个单选按钮时,您的表单才会提交。

    演示: Fiddle

    JS文件:

    function checkdata() {
        if ($('input[name^="chest"]:checked').length < 2) {
            alert("No radio checked");
            return false;
        }
        return true;
    }