Home > front end >  how to decrease or increase a number bu pressing the button Java script
how to decrease or increase a number bu pressing the button Java script

Time:03-24

Hey guys i've made buttons of ' ' and '-' and there is a number which i need to increase or decrease while pressing the or -, here my code but it isn't working. Will be glad if you can help me.

thank you!

button ></button><span >1</span><button ></button>

my JS

const plus = document.querySelector('.plus_minus'),minus = document.querySelector('.minus_plus');

let number = parseInt(document.querySelector('.number'));

plus.addEventListener('click',() => {number   ;});

minus.addEventListener('click',() => {number--;

});

CodePudding user response:

Anyway, I would suggest this:

HTML :

<button >-</button><span id="number">1</span><button > </button>

One class for "minus" button and one class for "plus" button. In your code you didn't differenciate them.

JS:

const minus = document.querySelector('.minus')
const plus = document.querySelector('.plus');

plus.addEventListener('click',() => document.getElementById("number").textContent  );

minus.addEventListener('click',() => document.getElementById("number").textContent--);

Add two listeners that directly increment/decrement the value.

CodePudding user response:

Right now you number variable is reference of the span element. You should get the value (innerHTML) of that

let number = parseInt(document.querySelector('.number').innerHTML);

In the event listener you should update the DOM (innertHTML of span) again after the value is updated.

    plus.addEventListener('click',() => {
     number   ;
     document.querySelector('.number').innerHTML = number;
    });

    minus.addEventListener('click',() => {
     number--;
     document.querySelector('.number').innerHTML = number;
    });
  • Related