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 never go below zero and should start on 0. Is there a way to do this simply in jquery? All the jquery plugins look at bit OTT for this operation.
Any help appreciated, ta.
something like this:
HTML:
<a id="minus" href="#">-</a>
<span id="value">0</span>
<a id="plus" href="#">+</a>
Javascript:
$(function(){
var valueElement = $('#value');
function incrementValue(e){
valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment, 0));
return false;
}
$('#plus').bind('click', {increment: 1}, incrementValue);
$('#minus').bind('click', {increment: -1}, incrementValue);
});
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.
This is actually built into jQuery - http://jqueryui.com/spinner/
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>
The jquery part
// initialize counter
var counter = 0;
// set the + functionality
$('#plus').click( function(){$('#display').html( ++counter )} );
// set the - functionality
$('#minus').click( function(){$('#display').html( (counter-1<0)?counter:--counter )} );
// initialize display
$('#display').html( counter );
and the html part
<span id="plus">+</span>
<span id="minus">-</span>
<div id="display"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With