Search code examples
javascriptjqueryhtmlajaxonkeyup

Update on keyup value of a text field


I have the following code :

{% for product in app.session.get('aBasket') %}
    <input id="product_quantity_{{ product['product_id'] }}" class="form-control quantity" type="text" value="{{ product['product_quantity'] }}" name="" onkeyup="calculatePrice({{ product['product_price'] }},{{ product['product_id'] }})">
    <span id="total_price_{{ product['product_id'] }}">{{ product['product_quantity'] * product['product_price'] }}</span>
{%endfor}
<div id="total_price_basket">TOTAL:0</div>

And my js function :

<script type="application/javascript">
    function calculatePrice(price, product_id) {
        var x = document.getElementById("product_quantity_"+product_id);
        var total_price = price * x.value;
        $("#total_price_"+product_id).html(total_price);
        $("#total_price_basket").html();
    }
</script>

So, the price for all products it works fine, the question is how to change the value for div>total_price_basket onkeyup? I must gather the amount of each product. Can you help me please? Thx in advance


Solution

  • I would make use of jQuery and get rid of obtrusive inline event handlers. For this HTML markup will change a little to use data attributes:

    {% for product in app.session.get('aBasket') %}
        <input data-id="{{ product['product_id'] }}" 
               data-price="{{ product['product_price'] }}"
               value="{{ product['product_quantity'] }}"
               class="form-control quantity" type="text">
        <span class="total" id="total_price_{{ product['product_id'] }}">{{ product['product_quantity'] * product['product_price'] }}</span>
    {%endfor}
    <div id="total_price_basket">TOTAL:0</div>
    

    JS:

    $('.quantity').on('keyup', function () {
    
        // Update individual price
        var price = $(this).data('price') * this.value;
        $('#total_price_' + $(this).data('id')).text(price);
    
        // Update total
        var total = 0;
        $('.total').each(function() {
            total += Number($(this).text());
        });
        $('#total_price_basket').text('TOTAL: ' + total);
    })
    // Trigger initial calculation if needed
    .trigger('keyup');
    

    Demo: http://jsfiddle.net/c64xfrpr/