Home > database >  reset button that won't reset properly in JS
reset button that won't reset properly in JS

Time:09-04

I've created 3 buttons, when you push one of them, indicates how many times you have clicked on that button.

I succeeded in making the button work properly. But the reset button I made is broken, which is the issue.

when you click the rest button it's going to '0' but after starting the button press again counting starts from '2' or '3', not from the number '1'.

please help me to sort this matter.

let btns=document.querySelectorAll('.box');
let reset=document.getElementById('rest');


    btns.forEach(btn => {   
        btn.addEventListener('click', () => {
                btn.innerText=    btn.value;
        });
});


reset.addEventListener('click', ()=>{
        btns.forEach(btn => {
                btn.innerText= 0;
        });     
       
});
button{
    height: 100px;
    width: 100px;
}
<button  value="0">0</button>
    <button  value="0">0</button>
    <button  value="0">0</button>

    <button id="rest">Reset</button>

CodePudding user response:

get the innerText and then add 1 to it per click.

  1. You're getting the value of the button, but are never setting it

  2. You're not parsing the value as an int. You can't use or calculating functions on strings, but getting a value or text from an element always returns a string type, not an integer.

let btns=document.querySelectorAll('.box');
let reset=document.getElementById('rest');


    btns.forEach(btn => {   
        btn.addEventListener('click', () => {
                btn.innerText= parseInt(btn.innerText)   1;
        });
});


reset.addEventListener('click', ()=>{
        btns.forEach(btn => {
                btn.innerText= 0;
        });     
       
});

Thanks to NoobishPro

CodePudding user response:

You are setting the btn text to 0 when reset. You also have to set the button value to 0. Which you are incrementing. As result when you reset only text is changed, value reamains the same.

let btns = document.querySelectorAll('.box')
let reset = document.getElementById('rest')

btns.forEach(btn => {   
  btn.addEventListener('click', () => {
    btn.innerText = parseInt(btn.innerText)   1
  })
})


reset.addEventListener('click', () => {
  btns.forEach(btn => {
    btn.innerText = 0
    btn.value = 0
  })
})
  • Related