开发者

Retrieving a form field hidden value thats located in table cell <td>

I have a table with a cell that contains a hidden input type. How do you go about accessing the value of this hidden input type?

HTML Table:

<table id = "tableId">
  <tr>
    <td>FirstName LastName</td>
    <td><input type="hidden" value="userId" /><td>
  </tr>

Javascript

    var table= document.getElementById("tableId");
    var tblTR = table.getElementsByTagName("tr");
    for (var i = 0; i<tblTR.length; i ++) {
        var tr = tblTR[i];
        var tds = tr.getElementsByTagName("td");
        console.debug(tds[0]); //gets the whole cell
        console.debug(tds[1].innerHTML); //gets content of cell, but not the actual value of the hidden input
}
开发者_如何学Python

With the second console.debug statement, the value I'm looking for is "userId" and not

<input type="hidden" value="userId" />

From what I understand, a td element cannot have a value attribute, therefore I can't simply just do a tds[i].value;.

Alternatively, is there another approach that can be used to store this hidden value?


You need to walk to the input tag itself

hiddenInputs = tds[1].getElementsByTagName("input");
console.debug(hiddenInputs[0].value);

or have a unique name or unique id to it and then you can access it directly.

<td><input type="hidden" id="inp1" value="userId" /><td>

document.getElementById("inp1").value

<td><input type="hidden" name="inp1" value="userId" /><td>

document.forms[0].inp1.value


The following works:

var inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++){
    if (inputs[i].type == 'hidden'){
        alert(inputs[i].value);
    }
}

JS Fiddle demo.

I'd suggest assigning the inputs[i].value to a variable, or an array, though rather than simply alert()-ing it:

var inputs = document.getElementsByTagName('input');
var values;

for (i=0; i<inputs.length; i++){
    if (inputs[i].type == 'hidden'){
        values = inputs[i].value;
    }
}


Give your input tag a name

example:

<input type="hidden" value="userId" name='userId'/>

Then you can access it:

<form ...name='theform'>
...

<input type="hidden" value="userId" name='userId'/>
...

</form>

The Javascript

var value = document.theform.userId.value;

this should do, you can ignore the table cells

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜