Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple plus and minus buttons

I am using - and + buttons to change the number of the text box, I am having troubles dealing with different text fields, here is my code:

var unit = 0;
var total;
// if user changes value in field
$('.field').change(function() {
  unit = this.value;
});
$('.add').click(function() {
  unit++;
  var $input = $(this).prevUntil('.sub');
  $input.val(unit);
  unit = unit;
});
$('.sub').click(function() {
  if (unit > 0) {
    unit--;
    var $input = $(this).nextUntil('.add');
    $input.val(unit);
  }
});
button {
  margin: 4px;
  cursor: pointer;
}
input {
  text-align: center;
  width: 40px;
  margin: 4px;
  color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
  field 1
  <button type="button" id="sub" class=sub>-</button>
  <input type="text" id="1" value=0 class=field>
  <button type="button" id="add" class=add>+</button>
</div>
<div id=field2>
  field 2
  <button type="button" id="sub2" class=sub>-</button>
  <input type="text" id="2" value=0 class=field>
  <button type="button" id="add2" class=add>+</button>
</div>

And here's the DEMO You can see in the demo that the values change correctly only if you click buttons on the same field, but if you alternate between fields the values don't change properly.

like image 789
jldc Avatar asked Dec 14 '22 13:12

jldc


2 Answers

This should be all you need:

$('.add').click(function () {
    $(this).prev().val(+$(this).prev().val() + 1);
});
$('.sub').click(function () {
    if ($(this).next().val() > 0) $(this).next().val(+$(this).next().val() - 1);
});

By using the unit variable you were tying both inputs together. And the plus in +$(this) is a shorthand way to take the string value from the input and convert it to a number.

jsFiddle example

like image 98
j08691 Avatar answered Dec 17 '22 03:12

j08691


You're using the same variable to hold the values of your two inputs. One simple option would be to use two variables instead of one:

var unit_1 = 0;
$('#add1').click(function() {
   unit_1++;
   var $input = $(this).prev();
   $input.val(unit_1);
});
/* Same idea for sub1 */

var unit_2 = 0;
$('#add2').click(function() {
   unit_2++;
   var $input = $(this).prev();
   $input.val(unit_2);
});
/* Same idea for sub2 */

and unit = unit just assigns the value of unit to itself, so that's no very useful and you can certainly leave it out.

like image 32
Thibault Sottiaux Avatar answered Dec 17 '22 02:12

Thibault Sottiaux