0

I have an spinner element made from two spans for + and - and an text input element in the middle that shows the quantity selected from the increase and decrease:

<div class="quantity-spinner"> 
 <span class="input-number-decrement">–</span><input class="input-number" type="text" value="1" min="0" max="10"><span class="input-number-increment">+</
</div>

I have two instances of this element, but currently when increasing the quantity for one of the elements it also controls the other one. My question is, how can I separate the two elements, so that they are controller independently.

Here is my JavaScript:

(function() {
  window.inputNumber = function(el) {
    var min = el.attr('min') || false;
    var max = el.attr('max') || false;
    var els = {};
    els.dec = el.prev();
    els.inc = el.next();
    el.each(function() {
      init($(this));
    });
    function init(el) {
      els.dec.on('click', decrement);
      els.inc.on('click', increment);
      function decrement() {
        var value = el[0].value;
        value--;
        if(!min || value >= min) {
          el[0].value = value;
        }
      }
      function increment() {
        var value = el[0].value;
        value++;
        if(!max || value <= max) {
          el[0].value = value++;
        }
      }
    }
  };
})();
inputNumber($('.input-number'));

Thank you in advance!

1
  • The event handlers will be invoked such that this will reference the DOM element involved. Commented May 28, 2015 at 13:54

1 Answer 1

2

try replacing

els.dec.on('click', decrement);
els.inc.on('click', increment);

by

el.prev().on('click', decrement);
el.next().on('click', increment);

you bug comes from the fact that els.dec and els.inc contain predecessors and successors for both counters

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.