Javascript单选按钮验证错误

时间:2013-05-19 21:51:14

标签: javascript validation radio-button

我无法使单选按钮验证正常工作。 复选框和textf字段很好,但单选按钮未验证为已选中,因此页面不会继续到成功页面。

<script>
        window.onload =function()
        {
            document.getElementById("pie_form").onsubmit = validateForm;
        }

        function validateForm()
        {
            var validName = validateTextBox("pie_name", "error_pie_name");
            var validFlavor = validateFlavor("flavor", "error_flavor");
            var validIceCream = validateCheckBox("ice_cream", "error_ice_cream");

            //if all fields validate go to next page
            return validName && validFlavor && validIceCream;
        }

        function validateTextBox(fieldId, errorId)
        {
            var text = document.getElementById(fieldId).value;
            var errorSpan = document.getElementById(errorId);

            if(text == "")
            {
                errorSpan.innerHTML = "* blank";
                return false;   //stay on this page
            }
            else
            {
                errorSpan.innerHTML = "";   //clear the error
                return true;    //go to success page
            }
        }


        function validateFlavor()
        {
            var flavor = document.getElementById("pie_form").flavor;
            var errorSpan = document.getElementById("error_flavor");
            errorSpan.innerHTML = "";

            if(!flavor.checked)
            {
                errorSpan.innerHTML = "* You must pick a flavor.";
                return false;
            }

            return true;
        }

        function validateCheckBox(fieldId, errorId)
        {
            var checkbox = document.getElementById(fieldId);
            var errorSpan = document.getElementById(errorId);
            errorSpan.innerHTML = "";

            //if you didn't check the checkbox show error
            if(!checkbox.checked)
            {
                errorSpan.innerHTML = "* You didn't agree to have Ice Cream?";
                return false;
            }

            //if you checked return true to say its valid
            return true;
        }

    </script>
</head>
<body>
    <h1>Pie Festival!</h1>

    <form id="pie_form" action="pie_success.html">
        <p>
            <label>Pie Name:
                <input type="text" id="pie_name" name="pie_name">
            </label>
            <span id="error_pie_name" class="error"></span>
        </p>            
        <p>
            Flavor:
            <span id="error_flavor" class="error"></span><br>
            <label><input type="radio" name="flavor" value="apple">Apple</label><br>
            <label><input type="radio" name="flavor" value="blueberry">Blueberry</label><br>
            <label><input type="radio" name="flavor" value="cherry">Cherry</label><br>
        </p>
        <p>
            <label>
                <input type="checkbox" id="ice_cream" name="ice_cream">
                Do you want Ice Cream?
            </label>
            <span id="error_ice_cream" class="error"></span>
        </p>

        <input type="submit" name="continue" value="Continue">
    </form>

4 个答案:

答案 0 :(得分:1)

document.getElementById("pie_form").flavor返回一个数组。您需要创建一个像isChecked这样的变量设置为false,循环遍历数组,并在选中其中一个单选按钮时将变量设置为true。然后继续编写脚本。

此代码有效:

function validateFlavor() {
    var flavor = document.getElementById("pie_form").flavor,
        errorSpan = document.getElementById("error_flavor"),
        isChecked = false,
        i;

    errorSpan.innerHTML = "";

    for (i = 0; i < flavor.length; i += 1) {
        if (flavor[i].checked) {
            isChecked = true;
            break;
        }
    }

    if (!isChecked) {
        errorSpan.innerHTML = "* You must pick a flavor.";
        return false;
    }

    return true;
}

这是一个fiddle

答案 1 :(得分:0)

我建议您尝试使用一些jQuery并使用:checked选择器,如下所示:

$('form').submit(function(e){

    e.preventDefault()

    if($('input[name=flavor]:checked').size() < 1){

        ... do ya thing...

    }else{

        $(this).submit()

    }

你应该真正使用jQuery,因为它很干净,更容易调试。

HERE THE WORKING FIDDLE

修改

选择器:checked基本上是一个CSS选择器,因此可用于通过jQuery选择器选择已检查的元素。您可以详细了解:checked选择器here

答案 2 :(得分:0)

你没有给无线电元素提供任何ID,所以你不能使用getelementbyid,而且无线电组给出了一个列表,所以你必须循环通过如下修改后的validateflavor函数:

function validateFlavor(fieldName, errorId) {
    var errorSpan = document.getElementById(errorId);
    errorSpan.innerHTML = "";
    var flavorgroups = document.getElementsByName(fieldName)

            for (var i = 0; i < flavorgroups.length; i++) {
                if (flavorgroups[i].checked) {
                return true; // checked
            }
            };

            // not checked, show error
            errorSpan.innerHTML = '* You must pick a flavor.';
            return false;
        }

答案 3 :(得分:0)

默认情况下始终选中一个单选按钮是个好主意,但有时候不适合。您可以将表单控件作为表单的属性引用,因此form.flavor将返回名称为 flavor 的控件的HTMLCollection。然后,您可以遍历它们以查看是否已选中一个,例如

function validate(formId) {
  var form = document.getElementById(formId);
  var radios = form.flavor;
  var oneChecked = false;

  for (var i=0, iLen=radios.length; i<iLen && !oneChecked; i++) {
    oneChecked = radios[i].checked
  }

  return oneChecked;
}