jquery - 如何选择动态生成的行的第 n 个孩子
问题描述
onfocusout() 从动态生成的行中访问数量和价格,将它们相乘并将其分配给总数。
我的表格:
<table id="dynamic-field" class="table table-striped table-bordered
dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<!-- <th> S.No </th> -->
<th> Product Name </th>
<th> Quantity </th>
<th> Price </th>
<th> Total </th>
<th style="text-align: center;"> <i class="fa fa-plus btn
btn-success" id="addProduct"></i></th>
</tr>
<tr>
<td style="width: 30%">
<select id="product_id" name="product_id[]"
class="formcontrol"
required="">
<option> --- Select ---</option>
@foreach($products as $product)
<option value="{{ $product->id }}"> {{ $product->name }}
</option>
@endforeach
</select>
</td>
<td style="width: 20%">
<input type="number" class="form-control" id="quantity"
ame="quantity[]" required="">
</td>
<td style="width: 20%">
<input type="number" class="form-control" id="price"
name="price[]" required="">
</td>
<td style="width: 20%">
<input type="number" class="form-control" id="total"
name="total[]" required="" >
</td>
<td style="text-align: center;">
<i class="fa fa-remove btn btn-danger"></i>
</td>
</tr>
</thead>
<tbody id="sales_information">
</tbody><!-- TBODY End -->
</table><!-- TABLE End -->
我尝试了以下代码,但这对我不起作用:
$(document).on('focusout', '#dynamic-field tr', function(e)
{
var price = $(this).find('td:nth-child(1)').val();
alert(price);
var quantity = $(this).find('td:nth-child(2)').val();
var result = price * quantity;
$('#total').val(result);
});
它在警报时显示我空白。
解决方案
You can't repeat ID's in a page so change the id's on the form controls to classes and then simply target those classes.
<input type="number" class="form-control quantity" name="quantity[]" required="">
Also you are trying to target wrong nth-child()
since `nth-child is not zero based like indexing is
$(document).on('focusout', '#dynamic-field tr :input', function(e)
{
var price = $(this).find('.price').val();
alert(price);
var quantity = $(this).find('.quantity').val();
var result = price * quantity;
$(this).find('.total').val(result);
});
推荐阅读
- c# - 格式化来自模型的动态 json 字符串以在 .net 视图中显示
- ios - Xamarin VS2019 无法使用配对的 mac 测试 iOS 应用程序
- javascript - 将 number 替换为将原始值乘以 0.75 的数字
- java - Canvas 对象是否在两次不同的 onDraw() 方法运行之间发生变化?
- javascript - 组件未使用 Redux 和 React 检测状态更改而不刷新组件
- apache-kafka - Micronaut kafka:无法完全使用一次 kafka 消息语义
- kubernetes - Kubernetes Headless Service 多接口 Pod
- class - AbstractMethodError:此方法必须在具体类类型中定义
- c++ - 仅使用单线程的 OpenMP
- synchronization - 同步问题。损坏的 ItemSyncTimestamps