2

I have created a simple calculator that takes variable #1 and variable #2 and multiplies them to generate a result.

When I change variable #1 the result instantly changes. However, when I change variable #2 the result remains unchanged.

How do I reconfigure my code so that the result instantly changes when either variable is altered?

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">

<h6>Variable #2</h6>
<input id="var2">

<h6>Result</h6>
<input readonly="readonly" id="result">

<script>
$(document).ready(function(){
    var mt=$("#var1");
    mt.keyup(function(){
        var total=isNaN(parseInt(mt.val()* $("#var2").val())) ? 0 :(mt.val()* $("#result").val())
        $("#result").val(total);
    });
});

</script>

3 Answers3

4

You have many things going wrong here, you need to bind keyup event in var1 textbox and var2 textbox both Also, your multiply formula is also wrong. Here is the desire code:

$(document).ready(function(){
    var mt=$("#var1,#var2");
    mt.keyup(function(){
    debugger;
        var total= 0;
        if(!isNaN(parseInt($("#var1").val())* parseInt(parseInt($("#var2").val())))){
          total=  parseInt($("#var1").val())* parseInt(parseInt($("#var2").val()));
        }
        
        $("#result").val(total);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">

<h6>Variable #2</h6>
<input id="var2">

<h6>Result</h6>
<input readonly="readonly" id="result">
Just code
  • 13,553
  • 10
  • 51
  • 93
0

Consider binding keyup events on both #var1 and #var2 inputs using the following jQuery syntax #var1, #var2 to achieve this desired behaviour, as shown:

$(document).ready(function(){

    // Select and bind keyup event to both "var" input elements using 
    // this syntax
    $('#var1, #var2') 
    .keyup(function(){ 

        // Adjust your keyup handler to perform calculation when keyup 
        // occurs on either input field
        var total= 0;
        if(!isNaN(parseInt($("#var1").val())* parseInt($("#var2").val()))){
             total = parseFloat($("#var1").val())* parseFloat($("#var2").val());
        }

        $("#result").val(total);
    });
});
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0

I just want to answer in vanilla Javascript for future reference of the problem.. I make var1,var2 class="input", then querySelect them both, then loop them, so that when you put any number to them, their value(product) will be produce in the id="result" if you did not put any number to them, the default value is zero(0) for both of them, so let say, you only put 10 to var1, then the output will only be 10, and if you put non numeric character, then the output is NaN.

    let input = document.querySelectorAll(".input");
    let var1 = document.querySelector("#var1");
    let var2 = document.querySelector("#var2");
    let output = document.querySelector("#result");


    function result(var1=0,var2=0) {
        output.value = Number(var1)*Number(var2);
    }

    for(let i=0;i<input.length;i++)
    {
        input[i].addEventListener(`keyup`,()=>result(var1.value,var2.value))
    }
<h6>Variable #1</h6>
    <input id="var1" class="input">

    <h6>Variable #2</h6>
    <input id="var2" class="input">

    <h6>Result</h6>
    <input readonly="readonly" id="result">

By the way you can also make the code much shorter by instead of putting the id var1,var2 value, you can instead just put the input class[0], and [1] it's the same..

so it can also be done this way.

    let input = document.querySelectorAll(".input");
    let output = document.querySelector("#result");


    function result(var1=0,var2=0) {
        output.value = Number(var1)*Number(var2);
    }

    for(let i=0;i<input.length;i++)
    {
        input[i].addEventListener(`keyup`,()=>result(input[0].value,input[1].value))
    }
<h6>Variable #1</h6>
<input id="var1" class="input">

<h6>Variable #2</h6>
<input id="var2" class="input">

<h6>Result</h6>
<input readonly="readonly" id="result">

By the way if you want to follow the same logic by using ternary operator,

let's follow his example, by using ternary operator,

change the result function to this.

    function result(var1=0,var2=0) {
    (var1*var2 ===0)? output.value=0: output.value=Number(var1) * Number(var2);
    }
Richard Ramos
  • 61
  • 1
  • 7
  • Don't use query selector for fetching id's. Simply use `document.getElementById`. – Blue Jul 30 '18 at 03:18
  • And consider demonstrating using a stack snippet. Will go a long way to male it easier to show us this solution actually works. – Blue Jul 30 '18 at 03:20
  • I need to use querySelectorAll, to demonstrate my second alternative solution to make the code much shorter, I don't know how to use code snippet I'm new here. ^_^ – Richard Ramos Jul 30 '18 at 03:24
  • You can still use `document.getElementById` for the result. No need to initialize a parser and walk through the dom, when you can do an indexed lookup. – Blue Jul 30 '18 at 03:26
  • Added my code snippet ^_^, I see, yes you are right ^_^ – Richard Ramos Jul 30 '18 at 03:29
  • What exactly does pure mean in this context? It's one function compared to another. – Blue Jul 30 '18 at 03:33
  • Added my code snippet ^_^, I see, yes you are right ^_^. but isn't querySelecting when you are also calling the id by putting # is the same as getting the id, I even read some debate here on stack, which is better, and the thread was closed by the admin, because it is an opinion based and not a fact. The admin said. Here. https://stackoverflow.com/questions/26848289/javascript-queryselector-vs-getelementbyid – Richard Ramos Jul 30 '18 at 03:36
  • Sorry I misread your comment, I deleted my pure function reasoning lol. – Richard Ramos Jul 30 '18 at 03:37
  • Yes you are right, I just tested it again, but I'm still clueless why the admin close that thread as opinion based, by the way.... – Richard Ramos Jul 30 '18 at 03:40
  • Opps, noo wait, it's different if you use other javascript engine, now it's reasonable the admin closed that thread.. – Richard Ramos Jul 30 '18 at 03:41
  • You say "The admin"...it was closed by 5 users. It can be considered opinion based, but the performance is quite clear. – Blue Jul 30 '18 at 03:42
  • Additionally, jsperf uses your browser to determine/run those tests. It's clearly 3 times faster (On your current engine), more widely supported, and designed for ids. – Blue Jul 30 '18 at 03:44
  • I see, sorry I'm new here, I don't know who close it, I see so user can also close a thread, anyways, yes you are right, but it is really hard considering I'm not the one who close that thread for the debate, so I don't know their reasoning why they said it is an opinion based.. And I also read that some JavaScript engine the result is different. So I really don't know if querySelecting an ID is better than using the getElementById. – Richard Ramos Jul 30 '18 at 03:45
  • yes, I know that, that's why I said the result is different based on some user comments, if you are using other engine. – Richard Ramos Jul 30 '18 at 03:46
  • Moderators have diamonds next to their names, and are community elected. As you gain rep on the site, you'll gain privileges to vote to close questions, and even the ability to delete questions. – Blue Jul 30 '18 at 03:49
  • Thanks, it is really hard, to say which is better, I read some article and comments, stating that although querySelecting is slower, but performance wise, it's negligible for human eyes, and if you are working on a big project, the ratio will close the gap, I mean, if for example you are selecting a multiple id, like 100 of id of different element, it is reasonable to put them to a nodes querySelecting them based on class, to make the runtime much faster.. but Seriously, you are right, getElementById is really fast.. – Richard Ramos Jul 30 '18 at 03:58
  • And I know you can use other methods like getting the tagName, etc.. Seriously, I think there is no better than the other on a bigger scale, maybe that is reason why that thread was closed as an opinion based. – Richard Ramos Jul 30 '18 at 04:06