sicisum
sicisum

Reputation: 31

Unable to display input[type='number'] value when changed by button

I have an input field along with buttons to update the input based on hitting + (Plus) and - (Minus):

$(document).on('click', '.qty-plus', function() {
  $(this).prev().val(+$(this).prev().val() + 1, )
})

$(document).on('click', '.qty-minus', function() {
  if ($(this).next().val() > 0)
    $(this).next().val(+$(this).next().val() - 1, )
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter adults">
  <input type="button" value="-" class="qty-minus">
  <input type="number" id="adults" min="1" placeholder="0" class="qty no-bdr" disabled>
  <input type="button" value="+" class="qty-plus">
</div>

The function works, however I cannot display the input value using:

$('input#adults').keyup(function () {
  $('#displayAdults').text($(this).val());
});

I've tried keyup, keydown, I cannot get this to work. I essentially want to show:

There are (number of) adults

Upvotes: 0

Views: 58

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Programmatically changing the value of an input does not raise an event. If you want that behaviour you need to do it manually using trigger(). I would suggest using the change event for this.

Also note that you can DRY up your code by using a common function to change the value along with data attributes to hold the value to change by, and also by using siblings() to get the related input from the buttons. Try this:

$(document).on('click', '.qty-change', function() {
  var $el = $(this);
  $el.siblings('input').val(function(i, v) {
    return parseInt(v) + $el.data('increment');
  }).trigger('change');
})

$('input#adults').on('change', function() {
  $('#displayAdults').text($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter adults">
  <button type="button" class="qty-change" data-increment="-1">-</button>
  <input type="number" id="adults" min="1" placeholder="0" class="qty no-bdr" value="0" disabled>
  <button type="button" class="qty-change" data-increment="1">+</button>
</div>

<div id="displayAdults"></div>

Upvotes: 1

Related Questions