Jquery Plus/Minus Incrementer

后端 未结 10 1150
挽巷
挽巷 2021-01-01 03:53

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

相关标签:
10条回答
  • 2021-01-01 04:19
    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.

    0 讨论(0)
  • 2021-01-01 04:20

    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>
    
    0 讨论(0)
  • 2021-01-01 04:21

    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> 
    
    0 讨论(0)
  • 2021-01-01 04:27

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

    0 讨论(0)
提交回复
热议问题