0

I search to make a simple counter in javascript.

He has a button to increase, and another to decrease the number.

Like it’s a limited counter, they can increase more that 4/4.

let addSkill = document.querySelector('#addSkill');
let subSkill = document.querySelector('#subSkill');
let counter = document.querySelector('#counter');

addSkill.addEventListener('click', () => {
  if (counter.value = 4) {
    counter.value = 4;
  } else {
    counter.value = parseInt(counter.value) + 1;
  }
});

subSkill.addEventListener('click', () => {
  if (counter.value <= 0) {
    counter.value = 0;
  } else {
    counter.value = parseInt(counter.value) - 1;
  }
});
<span class="badge badge-pill badge-info">
  <span id="counter">0</span>
  <span>/4</span>
</span>

<div class="modal-footer border-top-0">
  <button type="radio" class="btn btn-warning" id="subSkill" data-dismiss="modal">Later</button>
  <button type="radio" class="btn btn-primary" id="addSkill" data-dismiss="modal">Now</button>
</div>

2
  • 1
    Do you have a question? Commented Apr 22, 2021 at 20:58
  • you left an equal in your condition. if (counter.value == 4) Commented Apr 22, 2021 at 21:01

1 Answer 1

2

A <span> doesn't have value, you need to read and set it's text. Also = is not a comparison operator.

You can simplify this down to:

let addSkill = document.querySelector('#addSkill');
let subSkill = document.querySelector('#subSkill');
let counter = document.querySelector('#counter');

addSkill.addEventListener('click', () => {
  let count = parseInt(counter.textContent)
  if (count < 4) {
    counter.textContent = ++count;
  }
});

subSkill.addEventListener('click', () => {
  let count = parseInt(counter.textContent)
  if (count > 0) {
    counter.textContent = --count;
  }
});
<span class="badge badge-pill badge-info"><span id="counter">0</span><span>/4</span></span>

<button type="radio" class="btn btn-warning" id="subSkill" data-dismiss="modal">Later</button>
<button type="radio" class="btn btn-primary" id="addSkill" data-dismiss="modal">Now</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.