admin管理员组

文章数量:1183717

I'm wondering how can I get the value of an input in a specific table cell using javascript?

<td><input type="text"/></td>

I assume getting the innerHTML of a specific cell is quite simple, for example:

var x = document.getElementById("tabela").rows[2].cells[3].innerHTML

but this gives me just the input without it's value. Adding .value to the end of the line doesn't work. I would appreciate your help!

I'm wondering how can I get the value of an input in a specific table cell using javascript?

<td><input type="text"/></td>

I assume getting the innerHTML of a specific cell is quite simple, for example:

var x = document.getElementById("tabela").rows[2].cells[3].innerHTML

but this gives me just the input without it's value. Adding .value to the end of the line doesn't work. I would appreciate your help!

Share Improve this question edited Jun 20, 2014 at 17:10 potashin 44.6k11 gold badges89 silver badges112 bronze badges asked Jun 19, 2014 at 13:03 CasiCasi 1231 gold badge3 silver badges9 bronze badges 6
  • 1 Can you add a class or id attribute to your input field? – Lix Commented Jun 19, 2014 at 13:06
  • 1 Are you allowed to use jquery? – user2575725 Commented Jun 19, 2014 at 13:06
  • 3 Try this var x = document.getElementById("tabela").rows[2].cells[3].getElementsByTagName('input')[0].value – W.D. Commented Jun 19, 2014 at 13:06
  • 1 Correction to myself, I just realized what you're getting is the cell, rather than the input - yes, innerHTML would give you the input tag. But to actually get its value, you need to access, the tag itself - there are answers on this page that show how to do that. Getting the HTML for it is not useful, as you are better of getting the DOM node and manipulate that. – VLAZ Commented Jun 19, 2014 at 13:15
  • 1 thank you guys - that was my first ask on SO. I didnt know you are that fast and helpful :). Adding children[0].value to the end of the line gave me the input value... – Casi Commented Jun 19, 2014 at 13:41
 |  Show 1 more comment

4 Answers 4

Reset to default 20

If you don't have any id on the element you are after, then you could get the first child of the td by:

var x = document.getElementById("tabela").rows[n].cells[n].children[0].value;

Or if you want the first child to be specific to input then:

var x = document.getElementById("tabela").rows[n].cells[n].getElementsByTagName('input')[0].value;

You could use firstChild.value like this:

var x = document.getElementById("tabela").rows[2].cells[3].firstChild.value;

Demo

If you can provide id to your input element,

HTML

<td><input type="text" id="text1"/></td>

JS

var x = document.getElementById("text1").value;

You can use querySelector() DOM method:

document.querySelector('#tabela tr:nth-child(2) td:nth-child(3) > input').value

JSFiddle

本文标签: htmlHow can I get the value of an input in a specific table cell using javascriptStack Overflow