简体   繁体   中英

JavaScript multiple inputs onChange

I've got a problem. There's a shopping cart (shown as table) in the application based on Zend framework. Every row is a product in the shop basket. Every row has two form fields: quantity and value (= price*quantity).

I want to change the value by quantity (price*quantity) with the onChange event with JavaScript, but I don't know how to do this with number of rows > 1. Inputs are given in the foreach loop in the Zend view.

Is there any universal algorithm in JavaScript to solve this?

Does each value field have eg an ID attribute that can be derived from the ID of the quantity field? If so, then it's pretty quick and painless. Given:

<table id="basket">
    <tr class="basket-row">
        <td class="basket-quantity">
            <input type="text" id="product1234_quantity">
        </td>
        <td class="basket-subtotal">
            <input type="hidden" id="product1234_unitprice" value="20">
            <input type="text" readonly="readonly" id="product1234_subtotal">
        </td>
    </tr>
    <tr class="basket-row">
        <td class="basket-quantity">
            <input type="text" id="product5678_quantity">
        </td>
        <td class="basket-subtotal">
            <input type="hidden" id="product5678_unitprice" value="30">
            <input type="text" readonly="readonly" id="product5678_subtotal">
        </td>
    </tr>
</table>

Here, the unit price for each product is in a hidden attribute, but I don't know where your cart stores it. Let's assume you can get it from somewhere, and let's assume jQuery.

$('#basket').on('change','.basket-quantity input',function(e) {
    $('#'+this.id.replace('_quantity','_subtotal')).val(Number($('#'this.id.replace('_quantity','_unitprice')))*Number(this.value));
});

If you can't derive IDs from other IDs, you'd have to do some more complex DOM querying, but the point is, at runtime of the handler, you have to figure out what input you're updating.

You didn't specify what (if any) framework you are using. In plain JS this would require a lot of extra code to make it cross-browser compatible, to normalize event attachment and handling.

in for each you can use

$(this).index()

eg

$("#jieguo_qian table tr:nth-child(4) td").each(function(){
    var tindex = $(this).index() + 1;

so you can get the same td in the diff tr

th    th    th
td    td    td
td    td    td

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM