Search code examples
jqueryformskeyuponbluronfocus

values update issue in the form (jquery on function)


I have this simple order form which works fine exept one condition. Let me give you example. I fill up all fileds with numeric values, script counts number of items, their total value - no problem.

Now problem start if i decide to update the value and leave one of the fields blank (on blur function changes empty input into 0) but it it doesnt update the value to 0, so script doesnt recalculate the value of the order. (calculation script is triggered by keyup function).

What i would like to do is to keep functionality of (on blur and on focus functions) and have them connected to kayup function (so calculation can be done). Hope i explain myself clear. I tried some things but i cant get all the fuctions work together. Please help. Thank you very much in advance.

Working JSFiddle: https://jsfiddle.net/nitadesign/97tnrepg/53/

HTML:

<span class="txtbooking"><strong>SHOPPING BASKET</strong></span>
<div id="order_total" style="display: none;"></div>
<input type='submit' name='submit' id='submit' class="submitorder" value='Check Out' />  
<form name='packaging' action="test.php" method='post'>  
    <input name="totalUnits" type="hidden" id="totalUnits">  
    <p>Pack 1</p>
    <input type='text' class='pack' name='pack01' id='pack01' autocomplete='off' maxlength='3' value='0'/>
    <input type='hidden' class='pack' id='ppack01-price' name='ppack01-price' value='5' />

    <p>Pack 2</p>
    <input type='text' class='pack' name='pack02' id='pack02' autocomplete='off' maxlength='3' value='0'/>
    <input type='hidden' class='pack' id='ppack02-price' name='ppack02-price' value='7' />
    <p>Pack 3</p>
    <input type='text' class='pack' name='pack03' id='pack03' autocomplete='off' maxlength='3' value='0'/>
    <input type='hidden' class='pack' id='ppack03-price' name='ppack03-price' value='9' />
</form>

AND JS:

var orders = [];
$(".pack").keyup(function () {
    var curId = this.id.split("k")[1];
    var packPrice = parseFloat($('#ppack' + curId + '-price').val()).toFixed(2);
      var packUnit = parseInt($(this).val());
      var packTotal = parseInt(packUnit * packPrice);

    var order = null;   
    order = GetOrder(curId);

    if(order == null){
        order = {};
        order.id = curId;
        order.packPrice = packPrice;
        order.packUnit = packUnit;
        order.packTotal = packUnit * packPrice;
        orders.push(order);
    }
    else{
        order.packPrice = packPrice;
        order.packUnit = packUnit;
        order.packTotal = packUnit * packPrice;     
        UpdateOrders(order);
    }



    $(window).scroll(CalculateTotal)
    CalculateTotal();
    ;

});

function GetOrder(curId){
    var order = null;

    for(i = 0; i< orders.length; i++){
        if(orders[i].id == curId){
            order = orders[i];
            break;
        }
    }

    return order;
}

function UpdateOrders(order){
    for(i = 0; i< orders.length; i++){
        if(orders[i].id == order.id){
            orders[i] = order;
            break;
        }
    }   
}

function CalculateTotal(){


    var total = 0;
    for(i = 0; i< orders.length; i++){
        total = total + orders[i].packTotal;
    }
    console.log('total : ' + total);

    if(total > 0){
        var counter = 0;  
        $("input[name^=pack]").each(function(){
        if($(this).val() != "" && $(this).val() != 0) counter++;
        });
        console.log('counter : ' + counter);
        var totalUnits = 0; 
        $("input[name^=pack]").each(function(){
            packUnit = parseInt($(this).val());
            totalUnits = totalUnits + packUnit;
        });
        document.packaging.elements['totalUnits'].value = totalUnits;
        console.log('totalUnits : ' + totalUnits);

        $("#order_total").html('<table class="txts"><tr><td>Total Items:</td><td><strong>' + totalUnits + '<strong></td><tr><td>' + 'Order Subtotal:</td><td><strong>&pound;' + total.toFixed(2) + '</strong></td></tr></table>');
        $("#order_total").show();
        $('.submitorder').show();
    }
    if(total == 0){
        $("#order_total").html('<span class="txts">Your shopping basket is empty</span>');
        $("#order_total").show();
        $('.submitorder').hide();
    }

}

$("input[name^=pack]").on("change blur", function () {
    if (!this.value) {
        this.value = 0;
    }
});

$("input[name^=pack]").on("change focus", function () {
    if (this.value == "0") {
        this.value = "";
    }   
});

$(function(){
    $(window).scroll(CalculateTotal)
    CalculateTotal();
});

Solution

  • Check if the values are numeric if not set them to 0

    if (isNaN(packUnit)) {
          packUnit = 0;
        }
    

    demo: https://jsfiddle.net/97tnrepg/54/

    or https://jsfiddle.net/97tnrepg/55/