2016-02-24 45 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; 
 
    } 
 
}