I want to have a client side Plus / Minus system where a user can click the plus and a value is incremented by 1, minus and the value is decreased by 1, the value should nev
var currentValue = 0;
$(document).ready(function() {
$('#up').click(function() {
currentValue++;
});
$('#down').click(function() {
if (currentValue > 0) {
currentValue--;
}
});
});
Putting currentValue
in a textfield or other element would then be trivial.
Sure you can, e.g.:
<span id="minus"> - </span>
<span id="value"> 0 </span>
<span id="plus"> + </span>
<script type="text/javascript">
$(function() {
var value = parseInt($('#value').text(value));
$('#minus').click(function() {
if (value == 0) return;
value--;
$('#value').text(value);
}
$('#plus').click(function() {
value++;
$('#value').text(value);
}
});
</script>
If anyone's looking to have more than 1 incrementing input field on a page. Checks to see if .plus or .minus is clicked then changes the value of the sibling input, so you can have as many fields as you like.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.js"></script>
<div>
<a class="minus increment" href="#">-</a>
<input type="text" id="adults" size="10" value="0">
<a class="plus increment" href="#">+</a>
</div>
<div>
<a class="minus increment" href="#">-</a>
<input type="text" id="children" size="10" value="0">
<a class="plus increment" href="#">+</a>
</div>
<script type="text/javascript">
$(function(){
$('.increment').click(function() {
var valueElement = $('#'+$(this).siblings('input').attr('id'));
if($(this).hasClass('plus'))
{
valueElement.val(Math.max(parseInt(valueElement.val()) + 1));
}
else if (valueElement.val() > 0) // Stops the value going into negatives
{
valueElement.val(Math.max(parseInt(valueElement.val()) - 1));
}
return false;
});
});
</script>
This is actually built into jQuery - http://jqueryui.com/spinner/