1

is there a way in javascript or jquery where i can change my div text after input was changed?

        <div class="expression box">
        <div class="form-field"><input class="input" id="fn" oninput="validFirstNumber(parseInt(this.value))" type="text" size="40"></div>
        <div class="form-field">+</div>
        <div class="form-field"><input class="input" id="sn" oninput="validSecondNumber(parseInt(this.value))" type="text" size="40"></div>
        <div class="form-field">=</div>
        <div class="form-field"><div id="result">?</div></div>
        </div>

So i need to change div with result id after fn or sn become integer.

function validFirstNumber(number) {


 if (6 > number || number > 9) {
        document.getElementById('fn').style.color = 'Red';
    }
    calculate();
}

function validSecondNumber(number) {
    if (6 > number || number > 9) {
        document.getElementById('sn').style.color = 'Red';
    }
    calculate();
}

function calculate() {
    if (Number.isInteger(document.getElementById('fn')) && Number.isInteger((document.getElementById('sn')))) {
        document.getElementById('result').innerHTML = document.getElementById('fn') + document.getElementById('sn');
    }
}

I want to do it without buttons, action should trigger after i change numbers in inputs.

Liam
  • 27,717
  • 28
  • 128
  • 190
Ilia Levikov
  • 166
  • 1
  • 4
  • 13

1 Answers1

1

You can use on() method for change event on both input elements and update the result div with calculated result. You would write something like this;

$("#fn, #sn").on("change", function(event){
  // assuming your calculate() method is working correctly, you can call it here which updates the result div when either of inputs change 
  calculate();
  // otherwise you can write code which gets value from both input fields and update the "result" div
});

I hope this solves the problem.

tmw
  • 1,424
  • 1
  • 15
  • 26
  • yep, i did it something like that var calc = null; $(document).ready(function () { function calculate() { $('input').change(function () { var sum = 0; $fv = $('#fn').val(); $sn = $('#sn').val(); if ($.isNumeric($fv) && $.isNumeric($sn)) { sum = Number($fv) + Number($sn); $('#result').html(sum); } }) } calc = calculate(); }); – Ilia Levikov Jan 10 '18 at 12:12