如何在单选框被选中时获取同表格行内输入框的值?
表格中获取选中单选框对应输入框的值
实现步骤
- 把表格内所有带单选框的行的输入框值按结构存入数组,方便通过索引快速匹配
- 结合行索引(
index)和输入框在该行内的索引(i),精准获取选中单选框对应的输入框值
修正后的代码示例
HTML 结构
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="myTable"> <tr class="cell"> <td> <input type="radio" name="tableRadio"> <input type="text" placeholder="输入内容1"> </td> </tr> <tr class="cell"> <td> <input type="radio" name="tableRadio"> <input type="text" placeholder="输入内容2"> </td> </tr> </table>
JavaScript 逻辑
// 存储所有输入框值的二维数组,外层是行索引,内层是该行输入框的索引 const options = []; // 初始化数组,遍历表格行存入输入框值 $('#myTable tr').each(function(index) { const rowInputs = []; // 只处理带单选框的行 if ($(this).find('input:radio').length > 0) { $(this).find('input:text').each(function(i) { rowInputs.push($(this).val()); // 实时监听输入框变化,更新数组值 $(this).on('input', function() { options[index][i] = $(this).val(); }); }); options.push(rowInputs); } }); // 监听单选框选中事件,获取对应输入框值 $('#myTable input:radio').on('change', function() { if ($(this).is(':checked')) { const rowIndex = $(this).closest('tr').index(); // 获取当前行第一个输入框的值(如果有多个,可通过i索引指定) const targetValue = options[rowIndex][0]; console.log('选中行的输入框值:', targetValue); // 也可以直接实时获取输入框值,不需要数组的话: // const targetValue = $(this).siblings('input:text').val(); // console.log('选中行的输入框值:', targetValue); } });
代码说明
- 初始化时把每行的输入框值存入二维数组
options,同时监听输入框的输入事件,实时更新数组内容,保证数据同步 - 给每个单选框绑定
change事件,选中时通过closest('tr').index()获取行索引,再结合输入框的索引(示例中用0取第一个输入框),从数组中取出对应值 - 如果不需要提前存储所有值,也可以在单选框选中时直接通过
siblings或next等选择器实时获取相邻输入框的值,更简洁
内容的提问来源于stack exchange,提问作者anderson
相关产品推荐
相关产品推荐

