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

Getting textbox values inside table using jQuery

本文关键字:文本 jQuery 获取 使用      更新时间:2024-07-21

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());
  });
});

但我得到了未定义的值。

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

请帮我解决这个问题。

您可以使用

$('#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>

您只需使用:

$('#tb tr input[type=text]').each(function(){
  alert($(this).val());
});

该行使用选择器切换上下文

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

应该是

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

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