155
rated 0 times
[
161]
[
6]
/ answers: 1 / hits: 16733
/ 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