Home > Back-end >  user input in javascript need to reloade the page every time for change the value
user input in javascript need to reloade the page every time for change the value

Time:05-16

I build a web site that take from the user number and perform specific math operations by clicking in buttons, for example user type '100' and click at 15% button the app will print in the console log 15 now the user change the previous value at the input field to '80 and press the same button 15% it should print '12' but no it still the same result '15' if I want the result I need to reload the page, how can I make the result change every time the user change the input value in javascript, here simple code for more detail:

HTML:

<input type="number" id="ID">
<button id="Button">15%</button>

JAVASCRIPT:

const input= document.getElementById("ID");
const button = document.getElementById("Button");
button.addEventListener('click', ()=>{
 const operation = input.value * 0.15;
 console.log(operation);
});

CodePudding user response:

You're not resetting the input value from the memory stack, so when you try to call the variable value your program uses the first stored value to that variable. Try to instantiate your input variable in the event listener function so that each time you call this operation you are actually taking the new value in your variable.

    <div id="result"></div>
    <input type="number" id="ID">
<button id="Button">15%</button>


const button = document.getElementById("Button");
button.addEventListener('click', ()=>{
 const input= document.getElementById("ID");
 const operation = input.value * 0.15;
 console.log(operation);
 document.getElementById("result").innerHTML=`${operation}`;
});
  • Related