2012-01-20 68 views
0

我創建了一個帶有動態創建字段的表單,我試圖找到一種方法來驗證所有使用javascript的字段。我只想提醒用戶該字段爲空。這裏是我的代碼:Javascript動態創建表單字段驗證

<script> 
var counter = 0; 
function addInput(divName){ 
counter++; 
var Ai8ousa = document.createElement('div'); 
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>"; 
document.getElementById(divName).appendChild(Ai8ousa); 

} 

function validations(form){ 
var field; 
var i=0; 
do{ 
    field=form['field[]']; 
     if (field.value=='') 
      { 
      alert('The field is null!!!'); 
      return false; 
      } 
     i++; 
}while(i<counter); 
} 
</script> 


<form action="" method="post" onsubmit="return validations(this)" > 
<div id="dynamicInput"> 
Field : <input type="text" name="field[]" /> <br /> 
</div> 
<input type="button" value="New field" onClick="addInput('dynamicInput');"> 
<input type="submit" value="Submit" /> 

</form> 

我期待,將工作,但我顯然是錯誤的:( 有了這個代碼,如果我沒有按「新場」按鈕,然後按提交我會得到的警覺預期但在其他情況下我沒有得到任何 感謝您的時間反正,和對不起,如果我做了語法錯誤

回答

1
<script type="text/javascript"> 
var counter = 0; 
function addInput(divName){ 
counter++; 
var Ai8ousa = document.createElement('div'); 
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>"; 
document.getElementById(divName).appendChild(Ai8ousa); 

} 

function validations(form){ 
var field; 
var i=0; 
do{ 
    field=form[i]; 
     if (field.value=='') 
      { 
      alert('The field is null!!!'); 
      return false; 
      } 
     i++; 
}while(i<counter); 
} 
</script> 


<form action="" method="post" onsubmit="return validations(this)" > 
<div id="dynamicInput"> 
Field : <input type="text" name="field[]" /> <br /> 
</div> 
<input type="button" value="New field" onClick="addInput('dynamicInput');"> 
<input type="submit" value="Submit" /> 

</form> 

我不明白這一行:!field=form['field[]'];,所以我改變了它到field=form[i];

http://jsfiddle.net/sZ4sd/

+0

謝謝!這就像一個魅力!我以爲我曾經測試過,但我顯然做錯了! PS:我也有一個錯誤,我必須接受我等於計數器,所以正確的時候是:...} while(i <= counter) – VGe0rge