我有一个简单的形式
<tr>
<td> <input type="text" name="qty[]" placeholder="qty"/> </td>
<td> <input type="text" name="price[]" placeholder="price"/> </td>
<td> <input type="text" name="total[]" placeholder="Total"/> </td>
</tr>
Run Code Online (Sandbox Code Playgroud)
我们可以有多行与上面相同.
我需要的是当用户输入qty或需要更新price行时total.
我尝试了什么
$('input[name=\'qty[]\']').on('change keyup', function(){
var qty = $(this).val();
var price = $(this).parent('tr').find('input[name=\'price[]\']').val();
});
Run Code Online (Sandbox Code Playgroud)
price 是 undefined
或者有更简单的方法吗?请检查小提琴
更新:
.parent(..)选择当前元素集中每个元素的直接父元素.第一个参数过滤此集合.input元素的直接父元素是td元素,而不是tr元素.
更新小提琴
首先,考虑制作你的html:
<tr>
<td> <input type="number" name="qty[]" placeholder="qty"/> </td>
<td> <input type="number" name="price[]" placeholder="price"/> </td>
<td> <input type="number" name="total[]" placeholder="Total"/> </td>
</tr>
Run Code Online (Sandbox Code Playgroud)
也.到目前为止javascript:
jQuery(document).on("change , keyup" , "input[name='qty[]'] , input[name='price[]']" ,function(){
var parent_element = jQuery(this).closest("tr");
var qty = jQuery(parent_element).find("input[name='qty[]']").val();
var price = jQuery(parent_element).find("input[name='price[]']").val();
if( qty.trim() != "" && price.trim() != "")
{
jQuery(parent_element).find("input[name='total[]']").val( parseFloat(qty) *parseFloat(price) );
}
else
{
jQuery(parent_element).find("input[name='total[]']").val("");
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:更好的方法,适当考虑空字段
| 归档时间: |
|
| 查看次数: |
1437 次 |
| 最近记录: |