2012-02-21 13 views
0

我有以下代碼來檢查表單數據,我無法弄清楚爲什麼它不工作。Javascript檢查表單數據不起作用

<script type="text/javascript"> 
      function checkStuff() { 
       // By default, we plan to submit the form. 
       var formOkay = 1; 

       // Check to see if field_1 has a value. If not, we note that by changing our variable. 
       if(document.getElementById('requestorfirstname').value == '') 
        formOkay = 0; 

       // Let the user know something is wrong somehow. An alert is easiest. 
       alert('Requestor Name Required!'); 

       // If you return true the form will submit. If you return false it will not. 
       if(formOkay == 1) { 
        return true; 
       } else { 
        return false; 
       } 
      } 
     </script> 

現在這裏是html表單的一部分它的檢查onsubmit。

<input type="text" name="requestorfirstname" /> 

感謝您的幫助!

回答

4

document.getElementById查找由ID元素。您的字段沒有ID,它有一個NAME。

+0

就是這樣!在我修好之後,表格仍然完成,我需要更改哪些內容才能返回表單而不是繼續?謝謝 – Intelwalk 2012-02-21 15:37:11

+1

這一切都取決於你如何調用這個功能。 – 2012-02-21 15:46:56

+0

當按下按鈕時,我打電話給它。 – Intelwalk 2012-02-21 16:00:40

2

document.getElementById通過id選擇一個元素,而不是name

一些方法來解決這個問題:

+0

+1爲替代品的完整列表! – giorgio 2012-02-21 15:44:29

2

A name HTML元素上的屬性與id不一樣。您的輸入字段沒有標識,因此getElementById無法找到它。將元素更改爲:

<input type="text" name="requestorfirstname" id="requestorfirstname" /> 
              ^^^^^^^^^^^^^^^^^^^^^^^^ - add this