如果表单文本框为空,我将使用下面的代码检查它们。
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;
}
}我从我的超文本标记语言中调用这个JavaScript函数,如下所示。
<form id="form1" name="form1" method="post" onsubmit="return myFunction()" action="insert_alert.php" > 我的表单太长了,我不能创建变量,也不能对每个字段进行检查。如果有人能指导我减少劳动强度,我会很高兴的。
发布于 2012-10-24 14:48:46
您可以像这样迭代所有输入:
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-24 15:03:52
使用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>https://stackoverflow.com/questions/13044119
复制相似问题