Home > OS >  How to reset JavaScript code when input value is changed?
How to reset JavaScript code when input value is changed?

Time:04-19

I would like for the code to change its answer when I change the value of the input.

So let's say instead of 10, I would like it to tell me how much HP (health points) I will have at level 15. Is there any way I can do this? I'm not that experienced in Javascript.

So right now I coded it to default to 10 on all stats. My website tells me that at level 10, I have 895.4 hp. The only problem is that it won't stay at 15 when I try to press enter. It will just revert back to 10. Pretty much useless. Is there any way to keep that number 15 when I press enter?

var finalhp = 500;

let hpmultiplier = 1.06;

var hpvaluestring = document.querySelector('.hp').value;

var hpvalue = parseInt(hpvaluestring);

for (let i = 0; i < hpvalue; i  ) {
    var finalhp = finalhp * hpmultiplier
}

console.log(finalhp)
<form>
   <div>
      <input  id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
      <input  id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
   </div> 
</form>

CodePudding user response:

Add a form submit event listener to the form element and prevent form submission there.

<form onsubmit="submitForm(event)">
   <div>
      <input  id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
      <input  id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
   </div> 
</form>

Add a submitForm function inside a script tag

function submitForm(event){
    event.preventDefault();

   

    var finalhp = 500;
    
    let hpmultiplier = 1.06;
    
    var hpvaluestring = document.querySelector('.hp').value;
    
    var hpvalue = parseInt(hpvaluestring);
    
    for (let i = 0; i < hpvalue; i  ) {
       var finalhp = finalhp * hpmultiplier
    }

     console.log(finalhp)
}

CodePudding user response:

So mainly I'm just adding eventListeners to trigger the function calculateHP on input/slider value change. The function calculateHP contains the same logic that you shared. I did this so that the eventListeners can callback the function.

Try the following:

const input = document.querySelector('.hp')
const slider = document.querySelector('.slider')

slider.addEventListener('change', calculateHP)
input.addEventListener('change', calculateHP)

function calculateHP(){
  let multiplier = 1.06
  let level = Number(input.value)
  let HP = 500

  for(let i = 0; i<level; i  ){
    HP = HP * multiplier
  }
  return console.log(HP)
}
<div>
  <label>Level: </label>
  <input  id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
  <input  id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div> 

  • Related