从文本字段表中获取值 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16740281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get values from table of text fields javascript
提问by user2135738
I have a form which actually is a table of text fields. The html looks like this:
我有一个表单,它实际上是一个文本字段表。html 看起来像这样:
<form>
<table id="table">
<tr>
<th>Player</th>
<th>Number</th>
<th>Con.per.day</th>
<th>P.100.kg</th>
<th>P.day</th>
<th>I.month</th>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>Result</td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>Result</td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>Result</td>
</tr>
</table>
<input type="button" name="rank" value="Rank" onClick="rankPlayers(this.form)"/>
</form>
I would like to iterate all fields and get the values at the press of the button, but I get undefined returned in the console log. I don't want to use IDs for each field as I want to do some column operations (add, multiply). My script for the first column looks like this:
我想迭代所有字段并在按下按钮时获取值,但我在控制台日志中返回了 undefined 。我不想为每个字段使用 ID,因为我想做一些列操作(加、乘)。我的第一列脚本如下所示:
function rankPlayers(){
var table=document.getElementById("table");
for(var i=1; i<table.rows.length;i++){
console.log(table.rows[i].cells[0].value);
}
}
Any tips? Thanks
有小费吗?谢谢
回答by
You need to select the input from the cell:
您需要从单元格中选择输入:
// ------------------------------------v
console.log(table.rows[i].cells[0].firstChild.value);
If you could have siblings (even whitespace)around the inputs, then you can use the .children
collection to target the correct element.
如果您可以在输入周围有兄弟姐妹(甚至是空格),那么您可以使用.children
集合来定位正确的元素。
// ------------------------------------v
console.log(table.rows[i].cells[0].children[0].value);
回答by tymeJV
You can change your loop to:
您可以将循环更改为:
var table=document.getElementsByTagName("td");
for(var i=1; i<table.length;i++){
console.log(table[i].firstChild.value);
}
This gets all td
elements, loops them, and checks the firstChild
value
这将获取所有td
元素,循环它们并检查firstChild
值