2015-05-14 89 views
1

如何將字符串值傳遞給每個空字段的警報消息?如何將字符串值傳遞給javascript警報

我有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

如果有多個字段爲空 –

+0

爲什麼你不能爲每個變量設置if條件? – vidhya

+0

更好,你必須保持,如果條件所有個別領域 –

回答

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>

+0

http://jsfiddle.net/arunpjohny/tn2fvh4p/1/ –

+0

@Cloudburst http://jsfiddle.net/arunpjohny/tn2fvh4p/4/ –

+0

@Cloudburst http://jsfiddle.net/arunpjohny/tn2fvh4p/5/ –

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");

+0

這是非常有益的。非常感謝你 !愛它! – Cloudburst

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; 
    } 
} 
+0

你真了不起!非常感謝!將研究它!祝你有美好的一天! – Cloudburst

相關問題