Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  161] [ 6]  / answers: 1 / hits: 16727  / 9 Years ago, fri, june 26, 2015, 12:00:00

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.


More From » jquery

 Answers
5

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


[#66029] Thursday, June 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
catrinas

Total Points: 587
Total Questions: 100
Total Answers: 105

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;