Input Type Number. How to check if the up arrow or down arrow (mouse click) is pressed in a change event

I have an input type number

<input class="item" type="number" min="1" max="500" step="1" value="1" />

Now, to check for changes to this element, I used

$(".item:input").bind('change', function (e) {
      //doing something
 }

Now in this function, how can I check if the up arrow or down arrow of this element is pressed

I'm looking for something like the following

 $(".item:input").bind('change', function (e) {
     if(this up arrow pressed){
          print(up);
     }else{
          print(down);
     }

 }

How to do it?

+4
source share
3 answers

You can keep the old value for entering an attribute. try it

$(document).ready(function(){

    // assign oldVal data attribute at once on document ready
    $(".item:input").data('oldVal', $(".item:input").val());

     $(".item:input").change(function(){
            //get the newVal on change
            var newVal = $(this).val();
            // get the oldVal from data attribute 
            var oldVal = $(this).data('oldVal');
            // do stuff you need here
            if ( newVal > oldVal) {
                //UP arrow pressed
            } else {
                //DOWN arrow pressed
            }
            console.log( 'newVal is ' + newVal + ' oldVal was ' + oldVal);
            //store the newVal as the oldVal for the next change
            $(this).data('oldVal', newVal)
       })
       .focus(function(){
            // assign oldVal data attribute on input focus
            $(this).data('oldVal', $(this).val());
       });

});

Made by Fiddle for you

+4
source

Check this:

$(document).ready(function(){

$(".item:input").bind('keyup change click', function (e) {
      //doing something
 if(e.keyCode == 38) { //Enter keycode

   alert("up")
 }else if(e.keyCode == 40){
   alert("down");
 }


});

});

Demo: http://plnkr.co/edit/CjSG5VVYFZXr2tEkna5x?p=preview

+5
source

Just look at this fiddle. Not completed yet. But you will get an idea of ​​how to do this. fiddle

$(".item:input").bind('keyup click', function (e) {
      //doing something
 if(e.keyCode == 38) { //Enter keycode

   alert("up")
 }else if(e.keyCode == 40){
   alert("down");
 } else {
   $("input").change(function() {
    if (a> $("input").val()) {
      alert("down");
      a = $("input").val();
    } else
    {
      a = $("input").val();
      alert("up");
    }

  });
 }


});
+1
source

Source: https://habr.com/ru/post/1543968/


All Articles