jimi
jimi

Reputation: 213

calculation with changeable input field

i have the following problem:

when the value in the following input changes, the field #result should change.

 <input type="text" data-original-value="320" value="320" name="value1" id="value1" class="restorable">
 <input type="text" data-original-value="125" value="125" name="value2" id="value2" class="restorable">
 <input type="text" data-original-value="0.5" value="0.5" name="value3" id="value3" class="restorable">


    (function ($) {
     $(document).ready(function () {
         $('#coverage').keyup(function () {
             var raw = $('#value1').text()-( $('#value2').text()* $('#value3').text());
             var fixed = raw.toFixed();
             $('#result').text(fixed);
         });
     });
 }(jQuery));

it works when changing 1 value, but how to make it possible that

Upvotes: 0

Views: 218

Answers (2)

David Thomas
David Thomas

Reputation: 253308

I'd suggest:

// bind the 'keyup' event to the elements:
$('input.restorable').keyup(function(){
    // set the text of the '#result' element:
    $('#result').text(function(){
        // initialise a variable to hold the value:
        var total = 0;
        // get the relevant sibling 'input' elements, and iterate over them:
        $(this).siblings('input.restorable').each(function(){
            /* add the value, using parseFloat() to make it a numeric value,
               to that total variable: */
            total += parseFloat(this.value);
        })
        // set the text to the value of that variable
        return total;
    });
// trigger the function bound on 'keyup' by triggering a 'keyup' event:
}).trigger('keyup');

JS Fiddle demo.

References:

Upvotes: 2

Martin Bean
Martin Bean

Reputation: 39389

You need to create a jQuery function that does the calculation, and then attach event listeners to each of your fields:

$('#value1, #value2, #value3').on('keyup', function() {
    calculate();
});

var calculate = function() {
    var result = $('#value1').val() - ($('#value2').val() * $('#value3').val());
    $('#result').text(result.toFixed(2));
};

I’d re-factor this though, by adding a common class or data attribute to your HTML elements that identify them as part of your calculation, so you don’t have to hard-code their references in your jQuery script.

You’ll also need to add validation that users are actually entering numbers into your inputs.

Upvotes: 0

Related Questions