使用jQuery在表中获取文本框值

时间:2016-04-15 13:32:08

标签: javascript jquery

Html表

<table id="tb">
<tr>
  <th>First Name</th>
  <th>Last Name </th>
  <th>Coutry</th>
</tr>

<tr>
  <td><input type="text" id="FName"/> </td>
  <td><input type="text" id="LName"/> </td>
   <td><input type="text" id="Country"/> </td>
</tr>

<tr>
  <td><input type="text" id="FName"/> </td>
  <td><input type="text" id="LName"/> </td>
   <td><input type="text" id="Country"/> </td>
</tr>
</table>

Jquery的

//Here I am looping through all the rows in table
$('#tb tr').each(function(i, row) {
  //Here I need to loop the tr again ( i.e. row) 
  $(row, "input").each(function(i, sr) {
    //here  I want to get all the textbox values
    alert($(sr).eq(0).val());
    alert($(sr).eq(1).val());
    alert($(sr).eq(2).val());
  });
});

但是我得到了未定义的值。

我想从表格内的文本框中获取所有值。

请帮我解决问题。

3 个答案:

答案 0 :(得分:2)

该行使用选择器

切换上下文
$(row, "input").each(function (i, sr) {

应该是

$("input", row).each(function (i, sr) {

$(row).find("input").each(function (i, sr) {

答案 1 :(得分:2)

您可以使用

$('#tb tr').each(function(i, row) {
   $(this).find('input').each(function() {
     alert($(this).val())
   })
});

工作演示

$('#tb tr').each(function(i, row) {
   $(this).find('input').each(function() {
     alert($(this).val())
   })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tb">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Coutry</th>
  </tr>

  <tr>
    <td>
      <input type="text" id="FName" value="1" />
    </td>
    <td>
      <input type="text" id="LName" value="2" />
    </td>
    <td>
      <input type="text" id="Country" value="3" />
    </td>
  </tr>

  <tr>
    <td>
      <input type="text" id="FName" value="4" />
    </td>
    <td>
      <input type="text" id="LName" value="5" />
    </td>
    <td>
      <input type="text" id="Country" value="6" />
    </td>
  </tr>
</table>

答案 2 :(得分:2)

你可以使用:

$('#tb tr input[type=text]').each(function(){

  alert($(this).val());

});
相关问题