9

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!

6
  • 1
    Can you add a class or id attribute to your input field? Commented Jun 19, 2014 at 13:06
  • 1
    Are you allowed to use jquery? Commented Jun 19, 2014 at 13:06
  • 3
    Try this var x = document.getElementById("tabela").rows[2].cells[3].getElementsByTagName('input')[0].value 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. 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... Commented Jun 19, 2014 at 13:41

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

6

You could use firstChild.value like this:

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

Demo

Comments

1

If you can provide id to your input element,

HTML

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

JS

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

2 Comments

But if they're in a table, what is the ID?
OP did not mention any restriction for providing id to input elements. Else he could go by abhitalks answer
0

You can use querySelector() DOM method:

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

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.