如何为每个空字段将字符串值传递给警报消息?
我有w,t,a,c和s。例如,如果w为空,则应该给出 警告信息“必须填写必填字段”。同样的 为他人而战。
我的javascript:
function addvalidation(){
var w = document.forms["shop"]["w"].value;
var t = document.forms["shop"]["t"].value;
var a = document.forms["shop"]["a"].value;
var c = document.forms["shop"]["c"].value;
var s = document.forms["shop"]["s"].value;
var c = document.forms["shop"]["c"].value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}
答案 0 :(得分:4)
您可以过滤document.forms["shop"][e].value==""
的位置并加入它们以便在警告中显示
注意/更新:您需要加入密钥而不是值
e = Object.keys(document.forms["shop"]).filter(function(e){
return document.forms["shop"][e].value==""
});
errors = e.join(" ");
alert(errors +" are mandatory");
工作演示:
document.forms["shop"] =[] ;
document.forms["shop"]["w"] = {};
document.forms["shop"]["t"]={};
document.forms["shop"]["a"] ={};
document.forms["shop"]["c"]= {};
document.forms["shop"]["w"].value = "";
document.forms["shop"]["t"].value="abc";
document.forms["shop"]["a"].value = "";
document.forms["shop"]["c"].value="abcd";
e = Object.keys(document.forms["shop"]).filter(function(e){
return document.forms["shop"][e].value==""
});
errors = e.join(" ");
alert(errors +" are mandatory");

答案 1 :(得分:2)
您可以尝试类似
的内容
function addvalidation() {
var form = document.forms["workshop"];
var ef = ['w', 't', 'a', 'c', 's'].filter(function(f) {
return !form[f].value
})
if (ef.length) {
alert("Mandatory fields " + ef.join() + " must be filled out");
return false;
}
}

<form name="workshop" onsubmit="return addvalidation()">
<input name="w" />
<input name="t" />
<input name="a" />
<input name="c" />
<input name="s" />
<input type="submit" />
</form>
&#13;
答案 2 :(得分:0)
尝试使用此特定字段警报,
function addvalidation() {
var form = document.forms["workshop"];
var field="";
var ef = ['w', 't', 'a', 'c', 's'].filter(function(f) {
if(form[f].value=="" && field==""){
field=f;
}
})
if (field!="") {
alert("Mandatory field " + field + " must be filled out");
return false;
}
}