Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Plus/Minus Incrementer

Tags:

jquery

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.

like image 392
1'''' Avatar asked Feb 11 '10 14:02

1''''


5 Answers

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);

});
like image 58
Rowan Avatar answered Nov 28 '22 00:11

Rowan


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.

like image 35
Aistina Avatar answered Nov 28 '22 00:11

Aistina


This is actually built into jQuery - http://jqueryui.com/spinner/

like image 22
Andrew Avatar answered Nov 27 '22 22:11

Andrew


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>
like image 43
Felix Kling Avatar answered Nov 27 '22 22:11

Felix Kling


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>
like image 41
Gabriele Petrioli Avatar answered Nov 28 '22 00:11

Gabriele Petrioli