Casi
Casi

Reputation: 123

How can I get the value of an input in a specific table cell using javascript?

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!

Upvotes: 9

Views: 34133

Answers (4)

potashin
potashin

Reputation: 44581

You can use querySelector() DOM method:

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

JSFiddle

Upvotes: 0

naota
naota

Reputation: 4718

You could use firstChild.value like this:

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

Demo

Upvotes: 6

Mustafa sabir
Mustafa sabir

Reputation: 4360

If you can provide id to your input element,

HTML

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

JS

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

Upvotes: 1

Abhitalks
Abhitalks

Reputation: 28387

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;

Upvotes: 20

Related Questions