繁体   English   中英

如何从表格的最后一行获取输入类型文本的值

[英]How to get the value of input type text from the last row of a table

我的页面中有一个表格,每行都有输入类型文本,其中一个是 srno 我想使用 JavaScript 从表格的最后一行获取 srno 文本框的值。

这是我的 HTML 代码片段:

 <table id="vattable" class="table table-sm table-striped"> <thead class="thead-light"> <tr> <th style="width:50px">SRNo</th> </tr> </thead> <tbody> <tr> <td><input type="text" class="text-control input-sm" readonly name="srno[]" id="srno" value=1 style="text-align:right;max-width:40px;" maxlength="13" /></td> </tr> </tbody> </table>

实际上,我在 JavaScript 中的按钮单击事件上添加行,我想获取 srno 列的最后一个值,并在每次在表中创建行时给下一个 srno +1。 当页面加载时,我从数据库中选择数据并在这个表中获取数据,所以有时这个表可能已经有几行了,当我单击按钮创建行时,它应该采用最后一个 srno 并将 +1 添加到新行 srno。

如果您有类似的 HTML 结构,我认为这应该对您有用。

它的主要作用是:

  1. 使用name=srno扫描所有输入的表结构。
  2. 获取最后一个输入并登录 javascript 控制台。
  3. 您可以使用lastInput.value获取其值。

 function getLastInput() { //get all inputs with name srno in an array const allInputs = document.querySelectorAll('table tr input[name="srno[]"]'); //get the last input from the array by referring the highest index of the array const lastInput = allInputs[allInputs.length - 1]; return lastInput; } $(document).ready(function() { var rowcnt = $('#vattable tr').length; var count = rowcnt; $(document).on('click', '#addrow', function() { count = count + 1; var html_code = ''; html_code += '<tr id="row_id_' + count + '">'; html_code += '<td><input type="text" class="text-control input-sm" name="srno[]" id="srno" readonly style="text-align:right;width:40px" value="' + count + '"/></td>'; html_code += '</tr>'; $('#vattable').append(html_code); console.log(getLastInput()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="vattable"> <tr> <td> <input type="text" name="srno[]" value="1" /> </td> </tr> <tr> <td> <input type="text" name="srno[]" value="2" /> </td> </tr> <tr> <td> <input type="text" name="srno[]" value="3" /> </td> </tr> <tr> <td> <input type="text" name="srno[]" value="4" /> </td> </tr> </table> <button id="addrow">Add row</button>

编辑:

如果您的输入名称是srno[]请使用此srno[]

//get all inputs with name srno[] in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
console.log(lastInput);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM