如何使用类名验证单选按钮输入?

时间:2013-10-21 08:31:34

标签: javascript html html5 validation

请不要生气,因为我是java脚本的初学者。使用java脚本我想验证单选按钮输入。我编写了一个检查输入字段的脚本,如果它是空的,则会突出显示该字段。我正在使用输入字段的类名(reqd, reqdRight etc.)。有没有办法通过使用他们的类名验证无线电输入。

脚本是:

window.onload = initForms;

function initForms() {
    for (var i = 0; i < document.forms.length; i++) {
        document.forms[i].onsubmit = function() { return validForm(); }
    }
}

function validForm() {
    var allGood = true;
    var allTags = document.getElementsByTagName("*");

    for (var i = 0; i < allTags.length; i++) {
        if (!validTag(allTags[i])) {
            allGood = false;
        }
    }
    return allGood;

    function validTag(thisTag) {
        var outClass = "";
        var allClasses = thisTag.className.split(" ");

        for (var j = 0; j < allClasses.length; j++) {
            outClass += validBasedOnClass(allClasses[j]) + " ";
        }

        thisTag.className = outClass;

        if (outClass.indexOf("invalid") > -1) {
            thisTag.focus();
            if (thisTag.nodeName == "INPUT") {
                thisTag.select();
            }
            return false;
        }
        return true;

        function validBasedOnClass(thisClass) {
            var classBack = "";

            switch (thisClass) {
                case "":
                case "invalid":
                    break;
                case "reqd":
                    if (allGood && thisTag.value == "") {
                        classBack = "invalid ";
                    }
                    classBack += thisClass;
                    break;
                case "reqdRight":
                    if (allGood && thisTag.value == "") {
                        classBack = "invalid ";
                    }
                    classBack += thisClass;
                    break;
                case "reqddrpd":
                    if (allGood && thisTag.value == "") {
                        classBack = "invalid ";
                    }
                    classBack += thisClass;
                    break;

                default:
                    classBack += thisClass;
            }
            return classBack;
        }
    }
}

0 个答案:

没有答案