2014-01-20 43 views
0

這是我對動態字段驗證的編碼。 如果我使用這個函數,我得到'TypeError:document.getElementById(...)爲null'這種錯誤。TypeError:document.getElementById(...)在javascript中爲null

function sr_answer_val(){ 
    var cnt=parseInt(document.getElementById("add_field_cnt").value); 
    var submitAllow=true; 
    for(var i=1;i<cnt;i++){ 
    if(document.getElementById("cust_field_"+i).value ==''){ 
     alert('Answer Should be Mandatory'); 
     submitAllow=false; 
     return false;  
    } 
    } 
} 
+0

檢查HTML,如果真的有存在的所有元素(在執行時)要訪問。 – Sirko

+0

http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – basilikum

+0

請提供您的HTML標記了。檢查yur頁面中是否存在元素__add_field_cnt__和__cust_field_ __ –

回答

0

或許您的自定義字段並未全部定義,所以當您嘗試訪問其中一個時,它是未定義的。

檢查元素的accesing之前存在這樣的:

​​

演示:http://jsfiddle.net/IrvinDominin/X3ZnQ/

0

確實沒有在您的html中名爲「add_field_cnt」的元素。檢查是否沒有任何錯字。

0

您的元素 add_field_cnt是(DOM)未加載/創建。

我猜您加載頭的JS,而不是做這件事的body底部或使用document.ready

0

元素與ID傳遞給getElementById()不存在。所以,你可以做一個空檢查

var elem = document.getElementById("add_field_cnt"); 
if(typeof elem !== 'undefined' && elem !== null) { 
    var cnt = parseInt(document.getElementById(elem).value); 
    .......// do your stuff 
} 
0

沒有與ID add_field_cnt沒有元素所以你收到此錯誤

var cnt=parseInt(document.getElementById("add_field_cnt").value); 

請檢查你的元素創建或不add_field_cnt ID。

我希望如此。

相關問題