18910140161

JavaScript-jQuery在更改后获取附加输入的值-堆栈溢出

顺晟科技

2022-10-18 12:58:47

214

我有一个jQuery代码,我想对附加的字段进行计算示例如下:我有一个产品和它的价格,数量和总价总价的计算方法是价格乘以数量当我编写jQuery代码来计算总数时,它在页面加载时出现的默认元素上正常工作。但它不适用于通过“添加行”按钮

追加的字段更明显

的问题是,附加输入的值在更改

后无法访问。

enter image description here

<tr class="product-tr" data-product="1">
<td class="product-key">1</td>
<td>
    <div class="input-group">
        <input id="product-name" type="text" class="form-control" placeholder="{% translate 'Write product info' %}">
        <button type="button" class="remove-product btn btn-sm btn-light-danger" disabled>
            -
        </button>
        <button type="button" class="add-product btn btn-sm btn-light-success">
            +
        </button>
    </div>

    <input hidden name="product[1]['id']" type="number" class="product-id form-control">
</td>
<td>
    <input name="product[1]['price']" id="product-price-1" type="number" class="product-price form-control">
</td>
<td>
    <input name="product[1]['quantity']" id="product-quantity-1" min="1" value="1" type="number" class="product-quantity form-control">
</td>
<td>
    <input name="product[1]['total']" id="product-total-1" type="number" class="product-total form-control border-0 bg-light" disabled>
</td>

这是用于追加新行

jQuery代码
function recalculate_elements(){
    $( ".product-tr" ).each(function(index , e ) {
        index = index+1
        $(e).attr('data-product',index)
        $('.product-key', e).text(index)

        $('.product-id', e).attr('name', "product["+index+"]['id']")

        $('.product-price', e).attr('name', "product["+index+"]['price']")
        $('.product-price', e).attr('id', "product-price-"+index)

        $('.product-quantity', e).attr('name', "product["+index+"]['quantity']")
        $('.product-quantity', e).attr('id', "product-quantity-"+index)

        $('.product-total', e).attr('name', "product["+index+"]['total']")
        $('.product-total', e).attr('id', "product-total-"+index)
    })
}

这是计算总价

的jQuery代码
$('.invoice-table').on("keyup change", ".product-price, .product-quantity" , function() {
    parent_tr = $(this).parents('tr')
    id = parent_tr.attr('data-product')

    price = $('.product-price', parent_tr)
    quantity = $('.product-quantity', parent_tr)
    total = $('.product-total', parent_tr)

     alert(price.val())

    total.val(price.val() * quantity.val())

})

此代码获取空值

<代码>警报(price.Val())

顺晟科技:

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航