Miomir Dancevic Miomir Dancevic - 2 months ago 15
jQuery Question

Change value of first input jquery

I am using some spinner with font-awesome to style input type number with bootstrap but i have problem with event value, if I have more input type number on page it change value for all of them, but i need only for that one that is edited

Here is where i have problem

(function ($) {
$('.spinner .btn:first-of-type').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) + 1);
});
$('.spinner .btn:last-of-type').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
});
})(jQuery);


And here you can look full example

http://codepen.io/anon/pen/YGqLbv

Answer

You need to use the this keyword in the click event handlers to reference the button which was clicked. From that element you can traverse the DOM to find the related input. Try this:

$('.spinner .btn:first-of-type').on('click', function() {
  $(this).closest('.spinner').find('input').val(function(i, v) {
    return parseInt(v, 10) + 1;
  });
});
$('.spinner .btn:last-of-type').on('click', function() {
  $(this).closest('.spinner').find('input').val(function(i, v) {
    return parseInt(v, 10) - 1;
  });
});
.spinner {
  width: 100%;
}
.spinner input {
  text-align: left;
}
.input-group-btn-vertical {
  position: relative;
  white-space: nowrap;
  width: 1%;
  vertical-align: middle;
  display: table-cell;
}
.input-group-btn-vertical > .btn {
  display: block;
  float: none;
  width: 100%;
  max-width: 100%;
  padding: 8px;
  margin-left: -1px;
  position: relative;
  border-radius: 0;
}
.input-group-btn-vertical > .btn:first-child {
  border-top-right-radius: 4px;
}
.input-group-btn-vertical > .btn:last-child {
  margin-top: -2px;
  border-bottom-right-radius: 4px;
}
.input-group-btn-vertical i {
  position: absolute;
  top: 0;
  left: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <div class="page-header">
    <h1>Bootstrap 3 input-spinner</h1>
  </div>
  <div class="input-group spinner">
    <input type="text" class="form-control" value="42">
    <div class="input-group-btn-vertical">
      <button class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
      <button class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
    </div>
  </div>

  <div class="input-group spinner">
    <input type="text" class="form-control" value="42">
    <div class="input-group-btn-vertical">
      <button class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
      <button class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
    </div>
  </div>
</div>