2016-02-24 44 views
0

我想檢查,如果用戶在一個HTML表單 這裏進入實時右字符串的屬性值的The HTMLJS - 無法讀取空

<div class="col-md-2"> 
    <input class="form-control" name="nbequipement" id="nbequipement" placeholder="" type="text"> 
    <input type="button" value="Creer le tableau" onclick="GenerateTable()" /> 
    </div> 

下面是創建表的JavaScript:

function GenerateTable() 
{ 
    var edValue = document.getElementById("nbequipement"); 
    var s = edValue.value; 
    var table = document.createElement("table"); 
    table.className = "table table-condensed table-striped table-bordered" ; 
    table.id = "table"; 
    //CREATION DE L'ENTETE 
    var tableHeader = table.insertRow(-1); 
    var header1 = document.createElement("TH"); 
    header1.innerHTML = "Nom d'hote"; 
    //CREATION DE CHAQUE ROW DU TABLEAU 
    for (var i = 1 ; i <= s ; i++) { 
     //CREATION DE LA LIGNE 
     var row = table.insertRow(-1); 
     //CREATION DE CHAQUE CELLULES 
     var cell1 = row.insertCell(-1); 
     cell1.className = "col-md-1"; 
     cell1.id='container'+ i +'hostname'+ i + ''; 
     cell1.innerHTML = '<input class="input-sm" id="hostname' + i + '" placeholder="" type="text" onKeyPress="checkHostname('+cell1.id+', hostname'+i+')" onKeyUp="checkHostname('+cell1.id+', hostname'+i+')">' ; 
    } 

    var body = document.getElementById("tableSpace"); 
    body.innerHTML = ""; 
    body.appendChild(table); 

你可以看到,在 「小區1」 的innerHTML,有兩個監聽器:onkeypress事件&的onkeydown

而且當函數「CH eckhostname()」之稱,我有這樣的錯誤:

Uncaught TypeError: Cannot read property 'value' of nullcheckHostname @ template.js:128onkeyup @ templates.php:1 

這裏的功能:

function checkHostname(containerId, elementId) { 
    var textContainer = document.getElementById(elementId); 
    var texte = textContainer.value; 
    //CHECK THE VARIABLE "texte" 
    //var lblValue = document.getElementById("lblValue"); 
} 

我不明白爲什麼會產生這個錯誤。有些人談到了在編寫代碼之前執行的代碼,但在這種情況下似乎是不可能的。

+0

'onkeypress事件= 「checkHostname( '+ cell1.id +',主機名 '+ I +')」 onKeyUp' 您需要在報價中添加'elementId'('主機名 '+ I +''): – Cristy

回答

0

CRISTY的評論是你的答案。當您有:

cell1.innerHTML = '<input ... onKeyPress="checkHostname('+cell1.id+', hostname'+i+')" ...>' ; 

如果cell1.id是說 「foo」 和說是0,那麼這將被視爲像標記:

<input ... onKeyPress="checkHostname(foo0, hostname0)" ...> 

所以foo0主機名稱0將被視爲變量名稱,而不是字符串。所以你需要用引號包起來,例如

cell1.innerHTML = '<input ... onKeyPress="checkHostname(\''+cell1.id+'\', \'hostname'+i+'\')" ...>' ; 

所以它被看作是:

<input ... onKeyPress="checkHostname('foo0', 'hostname0')" ...>' 

當然這仍取決於與這些ID(當然,正確的ID)存在的文檔中時,代碼運行的元件。你說是這樣,所以它應該工作。

+0

謝謝您兩者都爲你的答案。 我總是遇到那些引號的麻煩...... – user3745776

-1

您的元素由於某種原因而不存在。但你可避免的錯誤:

function checkHostname(containerId, elementId) { 
 
    var textContainer = document.getElementById(elementId); 
 
    if(textContainer) { 
 
     var texte = textContainer.value; 
 
    } 
 
}