Alex Alex - 7 months ago 11
Javascript Question

How to use a function variable value in another function?

This is the HTML code:

<input type="number" class="small" value="0" step="any" id="input_1_0" name="input_25">
<input type="number" class="small" value="0" step="any" id="input_1_1" name="input_26">
<input type="number" class="small" value="0" step="any" id="input_1_2" name="input_27">
<p><b>Total:</b> <span id="total_cost">0</span></p>


and this is jQuery:

var total_cost;
jQuery(document).ready(function(){
jQuery('input').change(function() {
var input1 = Number((jQuery('#input_1_0').val()).replace(/[^0-9\.]+/g,""));
var input2 = Number((jQuery('#input_1_1').val()).replace(/[^0-9\.]+/g,""));
var input3 = Number((jQuery('#input_1_2').val()).replace(/[^0-9\.]+/g,""));
total_cost = input1 + input2 + input3;
});

jQuery(function(){
jQuery('#total_cost').text(total_cost);
});
});


For some reasons the Total is not being updated when numeric values are entered in input fields. Any help would be appreciated.

Answer

Because this code is executed asynchronously. You're wanting to update a variable when change is fired, and then have something update as a result, but there's nothing calling that second jQuery function. It runs once after the document is ready. The execution binds the event, then runs that second jQuery IIFE once. I don't even see why you want that in its own function. Just do this:

jQuery(document).ready(function(){
    jQuery('input').change(function() {
        var input1 = Number((jQuery('#input_1_0').val()).replace(/[^0-9\.]+/g,""));
        var input2 = Number((jQuery('#input_1_1').val()).replace(/[^0-9\.]+/g,""));
        var input3 = Number((jQuery('#input_1_2').val()).replace(/[^0-9\.]+/g,""));
        var total_cost = input1 + input2 + input3;
        jQuery('#total_cost').text(total_cost);
    });
});

This does not answer your question exactly, so here is how you would accomplish it on your criterion.

jQuery(document).ready(function() {
    var total_cost = 0;
    var update_total_cost = function() {  
        jQuery('#total_cost').text(total_cost);
    };

    jQuery('input').change(function() {
        var input1 = Number((jQuery('#input_1_0').val()).replace(/[^0-9\.]+/g,""));
        var input2 = Number((jQuery('#input_1_1').val()).replace(/[^0-9\.]+/g,""));
        var input3 = Number((jQuery('#input_1_2').val()).replace(/[^0-9\.]+/g,""));

        total_cost = input1 + input2 + input3;
        update_total_cost();
    });
});

This works because it gives the update text function a name and calls it after the event has fired.