0

here is my code :

<table><tr><td>hello</td>
       <td><input type="text" value="0" onkeypress="GetValue();" /></td>
       <td><input type="text" value="15"  /></td>
       </tr>
 </table>
   <script type="text/javascript">
   function GetValue(){
      //  ???

       }
   </script>

how can i access the value of the third td ( the td with the value 15 ) without using the the easy way and give the td an id and call it i want by using .parent() or .siblings() this is a simple example to simplify my work but in my actual project the input have their value binded from DB and it's much more complicated any help apreciated

Sora
  • 2,465
  • 18
  • 73
  • 146
  • is the target td just after the td with the input? or is there a possibility something is in the way? – Joseph Oct 24 '12 at 08:19
  • have a look at this jQuery function: http://api.jquery.com/nth-child-selector/ – 23tux Oct 24 '12 at 08:21

5 Answers5

3

You can do it via the :nth-child() selector.

JS code:

$('table td:nth-child(3) input').val();

DEMO

mas-designs
  • 7,498
  • 1
  • 31
  • 56
2

You should pass the DOM element to GetValue function:

<input type="text" value="0" onkeypress="GetValue(this);" />

And use jQuery methods to get the value from the next text field:

function GetValue(that) {
    var val = $(that).parent().next().find("input").val();
}

DEMO: http://jsfiddle.net/xzzUB/1/

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Could you include a jsfiddle version, because I tried your solution via jsfiddle and it does net seem to be working. – mas-designs Oct 24 '12 at 08:27
0

Change input like this:

<input type="text" value="0" onkeypress="GetValue(this);" />

and function to:

function GetValue(el){
  var sib = $(el).parent().siblings('td').last();
}
0

$("td:eq(2) input").val() will return 15

See: http://docs.jquery.com/Selectors/eq

Matt.C
  • 1,327
  • 7
  • 20
-1

HTML

<table id='theTable'><tr><td>hello</td>
       <td><input type="text" value="0" onkeypress="GetValue();" /></td>
       <td><input type="text" value="15"  /></td>
       </tr>
 </table>​​​

Use the nth-child() jQuery function

console.log($('#theTable td:nth-child(3)').children().val());​​​​​
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Doink
  • 1,158
  • 6
  • 10