尝试访问输入类型=“隐藏”时,getElementById为null

时间:2011-03-02 14:32:32

标签: javascript

我在使用getElementById获取<input type="hidden">并获取其值时遇到了问题。

这是我的功能,它位于第1页,用于显示我的选择以及让我返回并更改它们。

function showTerrain(terrain) {

if(document.getElementById('muni1') == null){  alert('is null'); }
else {alert('test:' + document.getElementById('muni1').value);}

  w = window.open("terrainChooser.php?terr=" + terrain + "&regID=1&muni=Rouyn-Noranda&parc=193", "", "width=500,height=450");

}

当showTerrain被激活时,它被发送到terrainChooser.php,它允许我选择3个值并返回信息:

window.opener.document.getElementById(elementID).innerHTML = 
   "<input readonly type='text' style='background-color:#eed8bb;border:0;' name='parcName" +    parcNum + "' value=\"" + txt + "\" />
    <input type='hidden' name='parcId" +parcNum + "' value='" + id + "' />
    <input type='hidden' name='regID" + parcNum + "' value='" + regID + "' />
    <input type='hidden' name='muni" + parcNum + "' value='" + muni +"' />";  

我知道我正在搜索的ID是唯一的,因为它在浏览器(firebug)中显示为:

<td id="parcSelected1"><input type="text" value="Forum" name="parcName1" style="background-color: rgb(238, 216, 187); border: 0pt none;" readonly="">
  <input type="hidden" value="193" name="parcId1">
  <input type="hidden" value="1" name="regID1">
  <input type="hidden" value="Rouyn-Noranda" name="muni1"></td>

不确定该怎么做...提前致谢!

5 个答案:

答案 0 :(得分:2)

您使用的是name属性,而不是id属性。变化

name='parcId" +parcNum + "'

id='parcId" +parcNum + "'

它应该有用。

答案 1 :(得分:1)

也许我是盲人但是......在你的html代码中,没有id为“muni1”的元素 - 只有一个带有名称的元素。改变:

<input type="hidden" value="Rouyn-Noranda" name="muni1">

为:

<input type="hidden" value="Rouyn-Noranda" name="muni1" id="muni1">

答案 2 :(得分:0)

“getElementById()”函数对元素 id 值进行操作,而不对元素 name 值进行操作。 (好吧,Internet Explorer认为“name”和“id”意思相同,但它只是不正确。其他浏览器不同意。)

给元素一个“id”:

<input type="hidden" value="Rouyn-Noranda" name="muni1" id="muni1">

答案 3 :(得分:0)

您正在设置“名称”而非“id”

答案 4 :(得分:0)

document.getElementById(elementID)

必须指向元素的ID字段,我相信你指向name属性。这只适用于IE。

<input type="hidden" value="Rouyn-Noranda" name="muni1"></td>

需要

<input type="hidden" value="Rouyn-Noranda" id="muni1"></td>