0

I have an input box surrounded by add and subtract button. You can enter numbers in the input box manually or you can press the add or subtract button to increase or decrease the number

HTML

 <button type="button" class="btn btn-info changeValue" onclick="decreaseValue()">-</button>
    <input type="number" class="form-control" name="quantity" id="addSub" value="0" placeholder="Quantity" required>
    <button type="button" class="btn btn-info changeValue" onclick="increaseValue()">+</button>

Javascript

function increaseValue() {
    var value = parseInt(document.getElementById('addSub').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('addSub').value = value;
  }

  function decreaseValue() {
    var value = parseInt(document.getElementById('addSub').value, 10);
    value = isNaN(value) ? 0 : value;
    value < 1 ? value = 1 : '';
    value--;
    document.getElementById('addSub').value = value;
  }

Now I have button to generate this input box dynamically. Multiple input box can be generated. All the add and sub buttons in the input box will however target the original input box. Is there a way to make it so that the add and sub buttons will always target the input box right next to it?

3
  • give each input a unique ID, and make the buttons pass this ID to your functions Commented Jul 9, 2019 at 0:05
  • I am using .append to create the inputbox and buttons on button click. There is not a way for me give a unique ID to each input box. Commented Jul 9, 2019 at 0:08
  • 1
    yes there is, when you create the input - perhaps show how you are dynamically creating these inputs in the question Commented Jul 9, 2019 at 0:09

2 Answers 2

2

When a button is clicked, check its textContent to see whether the associated input is to the left or the right of it, and then select either the target (the clicked element)'s previousElementSibling or nextElementSibling respectively:

document.addEventListener('click', ({ target }) => {
  if (!target.matches('button')) {
    return;
  }
  const doAdd = target.textContent === '+';
  const input = doAdd ? target.previousElementSibling : target.nextElementSibling;
  input.value = Number(input.value) + (doAdd ? 1 : -1);
});
<button>-</button>
<input type="number" value="0">
<button>+</button>

<button>-</button>
<input type="number" value="0">
<button>+</button>

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

Comments

-1

What you want to do is to give your input a unique id so you can pass it in input to the buttons to increase and decrease value

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.