You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery中点击表格行获取对应行的input值

问题:无法获取表格行内input的输入值

我尝试获取表格指定行的input值,但无法拿到td下对应元素的值。我用了这段代码:

var Clo_Bal = $(thisid).parent().parent().children('.7').html(); 

但没能成功获取。


表格生成代码

var results = '<div  style="overflow:auto;"><table id="myTable" class="table table-bordered table-hover dataTable no-footer">';
results += '<thead><tr><th scope="col"></th><th scope="col" >Sno</th><th scope="col" >Agentid</th><th scope="col">Date</th><th scope="col">AgentName</th><th scope="col">Op_Balance</th><th scope="col">SaleValue</th><th scope="col">PaidAmount</th><th scope="col">ClosingValue</th><th scope="col"></th></tr></thead></tbody>';
var k = 1;
for (var i = 0; i < msg.length; i++) {
  results += '<tr><td><input id="btn_poplate" type="button" onclick="getme(this)" name="submit" class="btn btn-primary" value="Update" /></td>';
  results += '<td scope="row"  style="text-align:center;">' + k + '</td>';
  results += '<th scope="row" class="1" style="text-align:center;">' + msg[i].AgentId + '</th>';
  results += '<td class="2">' + msg[i].inddate + '</td>';
  results += '<td class="3">' + msg[i].AgentName + '</td>';
  results += '<td class="4">' + msg[i].opp_balance + '</td>';
  results += '<td><input  id="txt_SaleValue" class="5" style="width:65px;" value="' + msg[i].salesvalue + '"/></td>';
  results += '<td><input id="txt_PaidAmount" class="6" style="width:65px;" value="' + msg[i].paidamount + '"/></td>';
  results += '<td><input  id="txt_CloBal" class="7" style="width:65px;" value="' + msg[i].clo_balance + '"/></td>';
  results += '<td><input  id="txt_Sno" class="8" style="width:65px;display:none;"  value="' + msg[i].sno + '"/></td></tr >';
  k++;
}
results += '</table></div>';
$("#div_BrandData").html(results);

表格截图

表格截图


解决方案

你的代码有两个关键问题:

  1. 选择器与取值方法错误:目标是input元素,需要用.val()获取输入值,而不是.html()(.html()用于获取元素内部的HTML内容);另外纯数字开头的类名.7在jQuery选择器中需要特殊处理,或者直接用属性选择器规避。
  2. DOM遍历逻辑冗余:用.closest('tr')可以直接定位到按钮所在的行,比多次parent()更简洁可靠。

修改后的代码示例:

function getme(btn) {
  // 定位当前按钮所在的表格行
  var targetRow = $(btn).closest('tr');
  // 获取class为7的input的值
  var Clo_Bal = targetRow.find('.7').val();
  // 或者用属性选择器彻底避免数字类名问题:
  // var Clo_Bal = targetRow.find('[class="7"]').val();
  console.log(Clo_Bal);
}

额外优化建议:

  • 不要用纯数字作为类名,不符合CSS命名规范,改用语义化命名比如col-closing-value,可读性更强也不会有选择器问题。
  • 避免重复id(比如多个按钮都用btn_poplate),id必须唯一,建议去掉id或用动态生成的id(如btn_poplate_${i})。

内容的提问来源于stack exchange,提问作者Akbar Shaik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:42:45