我知道这个问题已经被问过很多次了,我仔细阅读了大部分建议,但似乎没有一个解决方案适合我。
我有一个模式表,我允许用户在其中进行一些更改。然后我使用这些值来更新数据库中的数据。
我的表格行是通过回显 HTML 代码创建的
echo "<tr> ";
echo "<td > $row_counter </td>";
echo "<td style='width:200px' class='left_align' > $lstr_product_name </td>";
echo "<td > $lstr_department_name </td>";
echo "<td > <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='$lint_unit_cost' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='$lint_product_id' type='hidden'/> </td>";
echo "<td > $lint_quantity_counted </td>";
echo "<td > $lint_total_cost </td>";
要更新数据库中的正确值,我需要获取我知道可以获取的 product_id 名称
var x = document.getElementsByName("product_id")[0].value;
但是我需要获得正确的行索引才能发布正确的 product_id。
我尝试了以下方法:
alert($(this).index());
但这总是返回 0。我最接近的解决方案是使用
var rowID = $(this).closest('tr').index();
alert(rowID);
问题是我的可编辑单元格是“unit_cost”,它是 tr 中的第 4 个单元格。这意味着最近的 tr 不是单元格所在行的那一行,而是下面的那一行。
我试过了
alert( "Row id: " + $("#tbl_store_product_sizes tr").this.rowIndex );
但也没有运气。我已经没有想法了,这样做的正确方法是什么?
编辑 我所有的 javascript 代码都包含在 $(document).ready(function() 我正在使用以下代码观察 unit_cost 字段的变化
$(document.body).off( "change", ".unit_cost");
$(document.body).on('change', '.unit_cost', function(event)
{
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = document.getElementsByName("product_id")[rowID].value;
alert('The product id is: ' + x);
var unit_cost = document.getElementsByName("unit_cost")[rowID].value;
});
最佳答案
解释:-
因为两个输入都在同一个<td>
,因此在更改第一个时,您必须使用 .next()
获取下一个输入数据。
你需要像下面那样做:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
工作片段:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert('The corresponding row index is: '+ rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td style='width:200px' class='left_align'>2 </td>
<td>3 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='4' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='5' type="hidden"/> </td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td style='width:200px' class='left_align'>9 </td>
<td>10 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='11' /><input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='12' type="hidden"/> </td>
<td>13</td>
<td>14</td>
</tr>
</table>
关于javascript - 获取表javascript的行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47992699/