-1

I have table like this:

<tr id="t0" >
  <td id="0"></td>
  <td ><input name="0" style="width:20px;" type="text" />-
  <input name="1" style="width:20px;" type="text" />
  <button onclick="write(0)" >+</button></td>
</tr>
<tr id="t1" >
  <td id="1"></td>
  <td ><input name="1" style="width:20px;" type="text" />-
  <input name="2" style="width:20px;" type="text" />
  <button onclick="write(1)" >+</button></td>
</tr>

I need to get all values from input elements inside specific tr element. I tried following but nothing:

var t = $('table#tbl tr#'+id).find('input').val();
alert(t);

or

var t = $('tr'+id+':has(input)').val();
  alert(t);

but nothing... Can someone point me to the correct answer?

user1598696
  • 532
  • 1
  • 4
  • 20
  • 1
    What is `id`? As you know IDs are unique, why are you using those inefficient selectors? `$('#' + id)` is enough. – undefined Nov 10 '14 at 13:00
  • 1
    you need to add the "t" $('table#tbl tr#t'+id).find ... – MilMike Nov 10 '14 at 13:01
  • Also, please note that a valid id selector should start with a letter. http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Trufa Nov 10 '14 at 13:01
  • @Teemu Well, not in html5, but it doesn't mean that you should be using numbers, it is bad practice if you care about old browsers, is that what you meant by "nope"? :) – Trufa Nov 10 '14 at 13:10
  • 1
    @Teemu You are right but an id selector can't start with a number. id="1x" is ok but selector #1x isn't. But you can escape it, eg #\31 x – Nick Rice Nov 10 '14 at 13:14
  • Maybe I was a bit hasty, _id selector_ is not _id_ : ). – Teemu Nov 10 '14 at 13:22

1 Answers1

1

You can your .map to get all values since .val() gives you the value of the first input only. Each of your rows has an id; since IDs are unique, that's all you need to select a particular row.

var t = $('#t0').find('input').map(function() {
    return this.value;
}).get();
alert(t);

var t = $('#t0').find('input').map(function() {
  return this.value;
}).get();
alert( t );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr id="t0" >
  <td id="0"></td>
  <td ><input name="0" style="width:20px;" type="text" value="test 1" />-
  <input name="1" style="width:20px;" type="text" value="test 2" />
  <button onclick="write(0)" >+</button></td>
</tr>
<tr id="t1" >
  <td id="1"></td>
  <td ><input name="1" style="width:20px;" type="text" />-
  <input name="2" style="width:20px;" type="text" />
  <button onclick="write(1)" >+</button></td>
</tr>
  </table>

Reference:

  1. .map() | jQuery API Documentation
PeterKA
  • 21,234
  • 4
  • 21
  • 44