0

我正在使用下面的代码来检查我的表单文本框,如果它们是空白的。

function myFunction(){
    var week_no=document.getElementById("week_no").value;
    var date_rep=document.getElementById("date_rep").value;


    if(week_no==null || week_no=="")
    {
    alert("week_no field must be filled out");
    document.getElementById("week_no").style.background="pink";
    document.getElementById("week_no").focus();
    return false ;
    }
    if(date_rep==null || date_rep=="")
     {
    alert("date_rep field must be filled out");
    document.getElementById("date_rep").style.background="pink";
    document.getElementById("date_rep").focus();

    return false;
    }
}

我从我的 HTML 中调用这个 JavaScript 函数,如下所示。

<form id="form1" name="form1" method="post" onsubmit="return myFunction()" action="insert_alert.php" >    

我的表格太长了,我无法制作变量并对各个字段进行检查。如果有人指导我减少劳动,那将是我的荣幸。

4

2 回答 2

0

您可以像这样迭代所有输入:

var inputs =  document.getElementById("form1").getElementsByTagName("input");
for(var i=0;i<inputs.length;i++) {
    var inp = inputs[i];
    if(inp.value == null || inp.value == "") {
        inp.style.background="pink";
    }
}
于 2012-10-24T06:48:45.803 回答
0

使用jquery方法:

<script>
    function myFunction() {
        var errorString = "";
        $("#form1 input[type='text']").css("background-color", "");
        $("#form1 input[type='text']").each(function (index, element) {
            if (errorString == "") {
                if (!$(element).val()) {
                    errorString += $(element).attr("id") + " field must be filled out";
                    $(element).css("background-color", "pink");
                }
            }
        });
        if (errorString) {
            alert(errorString);
            return false;
        }
        return true;
    }

</script>


<form id="form1" name="form1" method="post" onsubmit="return myFunction()" action="insert_alert.php" >
    <input type="text" id="week_no" />
    <input type="text" id="date_rep" />
    <input type="submit" value="go" />
</form>
于 2012-10-24T07:03:52.267 回答