Increment value of textinput with jquery like spin

2020-02-26 01:39发布

问题:

Trying to create a simple spinner effect with Jquery, i.e. two buttons (up & down) with a text field. The upbutton increases the value while the down button decreses the value. increment steps + or - 1.

Any suggestions as ui.spinner is most def. not working and I am new to jquery. musty be something like $(#up).click (function ( /*SOMETHING GOES IN HERE but what?*/ )) and likewise for #down. both to set adjust the input text field say id #test as above.

回答1:

Maybe something like:

$(document).ready( function() {
  var el = $('#test');
  function change( amt ) {
    el.val( parseInt( el.val(), 10 ) + amt );
  }

  $('#up').click( function() {
    change( 1 );
  } );
  $('#down').click( function() {
    change( -1 );
  } );
} );


回答2:

Demo: http://jsbin.com/akiki

<button id="inc">+</button>
<button id="dec">-</button>
<input type="text" name="qty" value="0" />

<script type="text/javascript">
  $(function(){
    $("#inc").click(function(){
      $(":text[name='qty']").val( Number($(":text[name='qty']").val()) + 1 );
    });
    $("#dec").click(function(){
      $(":text[name='qty']").val( Number($(":text[name='qty']").val()) - 1 );
    });
  });
</script>


回答3:

Have a look at this demo - I have found that this works the best of all the ones I've tried

Especially if you are using jquery ui themes

http://btburnett.com/spinner/example/example.html



回答4:

With the base code by @rfunduk I created this:

$(document).ready( function() {

    var el = $('#quantity_wanted');

    function change( amt ) {

        if (el.val() == '') {
            var newValue = 1;
        } else {
            var newValue = parseInt( el.val(), 10 ) + amt;
        }

        if (newValue > 0) {
            el.val( newValue );
        }

    }

    $('#cart_quantity_up').click( function() {
        change( 1 );
    } );

    $('#cart_quantity_down').click( function() {
        change( -1 );
    } );
} );