如何在动态表中定位同一行中的元素
How do I locate elements in the same row as another in a dynamic table?
我正在制作一个页面,其中包含一个带有添加行按钮的表。它是一个供用户输入数据的表,最终将提交到数据库。
目前,我在每一行都有一个价格和数量字段。当它们中的任何一个发生变化时,我想计算总数并将其写入另一个单元格。
这是我的事件处理程序(封装在$(document).ready()
中):
$(".quantity_input, .price_input").change(function () {
console.log(this.value);
cal_total();
});
这是我当前的代码:
function cal_total() {
if (isNaN(parseFloat(this.value))) {
alert("You must enter a numeric value.");
this.value = "";
return;
}
var cell = this.parentNode;
var row = cell.parentNode;
var total = parseFloat($("#items_table tr").eq(row.index).find("td").eq(3).find("input").first().val()) * parseFloat($("#items_table tr").eq(row.index).find("td").eq(4).find("input").first().val());
if (!isNaN(total)) {
$("#items_table tr").eq(row.index).find("td").eq(5).html(total.toFixed(2));
}
}
这就是输入的样子:
<input type='text' class='fancy_form quantity_input' name='quantities[]' size='4' style='text-align:center;border-bottom:none;'>
除了我最初的问题之外,该活动从未被解雇。有人知道为什么吗?
但更重要的是,这是检索值的最佳方式吗?我真的不这么认为,但我想不出比这更聪明的办法了。
谢谢!
您必须将参数传递给calc_total以定义输入或tr
试试这个代码
$(".quantity_input, .price_input").change(function () {
$(".quantity_input, .price_input").change(function () {
cal_total(this);
});
});
function cal_total(elem){
var row=$(elem).closest("tr")
var quantity=row.find(".quantity_input").val()-0
var price=row.find(".price_input").val()-0
var total=quantity * price
row.find(".totl_input").val(total)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
</table>
相关文章:
- 禁用“基于同一行上的另一个元素进行选择”
- 无法破解pass-css插件以使两个输入元素出现在一行中
- 使用setAttribute将id设置为元素最后一行的td
- 在 CSS 中有一个单独的伪选择器,以显示有关一行中多个元素的信息
- 当我隐藏页面上的元素时,光标会跳到顶部而不是下一行.我该如何阻止这种情况
- 如何使用 jQuery 检查元素是否中断到下一行
- 一行仅用于内容可编辑元素
- 阻止浮动 HTML 元素下降到下一行
- 如何使用一行代码获取字符串数组的最后一个元素
- jQuery-如果元素在同一行,则具有不同的事件
- 选择表中的一行或多行,并为该元素提供背景的技术
- 用一行(jQuery)连接不同框架中的2个元素
- 如何在一行中将数组元素传递给日志参数集
- 如何在动态表中定位同一行中的元素
- 使用javascript在元素中选择一行文本
- 如何使用jQuery将表中同一行的另一个元素作为目标
- D3.js:在调用path-元素属性的函数中,生成一行和d-object是未定义的
- Jquery移动到下一行's输入元素的id
- 附加到元素的脚本标记会在.append()之后的下一行之前运行吗?
- 检测哪一行JS正在操作给定的HTML元素