//检查必填字段
//(通用的校验必填项不能为空(包括input框,单选框,复选框,文本域))
var elem = document.getElementById("age");
function checkRequired(elem){
var name = elem.name;
if(elem.type == "checkbox" || elem.type == "radio"){
var results=[];
results.numChecked = 0;
var input = document.getElementsByTagName("input");
for(var i=0;i<input.length;i++){
if(input[i].name == name){
results.push(input[i]);
if(input[i].checked){
results.numChecked++;
}
}
}
return results.numChecked;
}else{
return elem.value.length > 0 && elem.value != elem.defaultValue;
}
}
//-----------------------------------------------------
//检查输入元素是否键入了信息的通用函数
function checkRequired(elem){
if(elem.type == "checkbox" || elem.type == "radio")
return getInputsByName(elem.name).numChecked;
else
return elem.value.length > 0 && elem.value != elem.defaultValue;
}
//找出指定name的所有input元素(对查找 以及处理复选框或单选框十分有用)
function getInputsByName(name){
var results=[];
results.numChecked = 0;
var input = document.getElementsByTagName("input");
for(var i=0;i<input.length;i++){
if(input[i].name == name){
results.push(input[i]);
if(input[i].checked){
results.numChecked++;
}
}
}
return results;
}
window.onload = function(){
document.getElementsByTagName("form")[0].onsubmit=function(){
var elem = document.getElementById("age");
if(!checkRequired(elem)){
alert("Required field is empty "+"you must be over 13 to use this site.");
return false;
}
var elem = document.getElementById("name");
if(!checkRequired(elem)){
alert("Required field is empty - please provide ");
return false;
}
};
};
通用的校验必填项不能为空(包括input框,单选框,复选框,文本域)
最新推荐文章于 2023-07-24 11:20:03 发布