2013-09-05 24 views
2

您好我想查一個形式,如果輸入的值是空的,但我不知道什麼做到這一點的最好辦法是,所以我想這:JS形式檢查空

function checkform() 
     { 
     if (document.getElementById("promotioncode").value == "") 
     { 
      // something is wrong 
      alert('There is a problem with the first field'); 
      return false; 
     } 

     return true; 
     } 

HTML:

<form id="orderForm" onSubmit="return checkform()"> 
    <input name="promotioncode" id="promotioncode" type="text" /> 
    <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/> 
<input class="submit" type="submit" value="Submit"/> 
     </form> 

有沒有人有想法或某種更好的解決方案? thx的任何幫助:)

+0

還有其他的方法可以做到這一點,但你已經有最好的辦法 – Krishna

+0

這應該工作,並且不會讓表單被提交,如果該字段爲空。請注意,這往往會讓那些在現場輸入亂碼以繞過規則的人感到挫敗。當服務器獲得數據時,這會在數據中留下一個非空白的,無關緊要的值。從長遠來看,它可能會弄亂報告和其他處理。 –

+2

既然你標記了這個[標籤:HTML5],'required'屬性應該這樣做......除此之外,我會建議附加處理程序與DOM方法,而不是內聯屬性。 – Bergi

回答

4

添加required屬性是現代瀏覽器的好方法。但是,您很可能還需要支持舊版瀏覽器。此JavaScript會:

  • 驗證每required輸入(表單內提交),填寫完畢。
  • 如果瀏覽器尚不支持required屬性,則僅提供alert行爲。

的JavaScript:

function checkform(form) { 
    // get all the inputs within the submitted form 
    var inputs = form.getElementsByTagName('input'); 
    for (var i = 0; i < inputs.length; i++) { 
     // only validate the inputs that have the required attribute 
     if(inputs[i].hasAttribute("required")){ 
      if(inputs[i].value == ""){ 
       // found an empty field that is required 
       alert("Please fill all required fields"); 
       return false; 
      } 
     } 
    } 
    return true; 
} 

一定要添加this到checkform功能,無需檢查未提交inputs

<form id="orderForm" onsubmit="return checkform(this)"> 
    <input name="promotioncode" id="promotioncode" type="text" required /> 
    <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/> 
    <input class="submit" type="submit" value="Submit"/> 
</form> 
2

根據您打算支持哪些瀏覽器,您可以使用HTML5所需的屬性,並放棄JS。

<input name="promotioncode" id="promotioncode" type="text" required /> 

Fiddle.

1

演示:http://jsfiddle.net/techsin/tnJ7H/4/#

var form = document.getElementById('orderForm'), 
    inputs=[], ids= ['price','promotioncode']; 


//findInputs 
fi(form); 
//main logic is here 
form.onsubmit = function(e){ 
    var c=true; 
    inputs.forEach(function(e){ if(!e.value) {c=false; return c;} }); 
    if(!c) e.preventDefault(); 
}; 


//findInputs function 
function fi(x){ 
var f = x.children,l=f.length; 
while (l) { 
    ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); }); 
    l--; 
} 
} 

說明:

  • 要停止提交您使用event.preventDefault過程。事件是傳遞給函數onsubmit事件的參數。它可以在html或addeventlistner中。
  • 要開始提交,您必須停止防止默認執行​​。
  • 您只能通過重新調整false來打破forEach循環。不使用休息;與正常循環一樣..
  • 我已經把ID數組放在哪裏你可以把這個論壇將檢查,如果他們是空的或沒有元素的名稱。
  • 查找輸入法只是簡單地遍歷表單元素的子元素,看看他們的id是否已經在id數組中被識別。如果是,那麼它將該元素添加到輸入中,稍後在提交之前檢查其中是否有值。如果沒有,它會阻止默認。