Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting number input spinner click

I've got a simple number input with a min="1" and max="12" value set, this is used as an hour selector. I'd like it to cycle through the hours, so when you get to 12 and press the "up" arrow, it goes back to 1 and vice-versa as well.

Right now I have this mostly working:

var inputTimer = null;

function cycle(element) {
  if (element.attributes.max && element.attributes.min) {
    var prevVal = element.value;
    inputTimer = setTimeout(function() {
      if (prevVal === element.attributes.max.value) {
        element.value = element.attributes.min.value;
      } else if (prevVal === element.attributes.min.value) {
        element.value = element.attributes.max.value;
      }
    }, 50);
  }
}

$("input[type='number']")
  .on("mousedown", function(e) {
    //this event happens before the `input` event!
    cycle(this);
  }).on('keydown', function(e) {
    //up & down arrow keys
    //this event happens before the `input` event!
    if (e.keyCode === 38 || e.keyCode === 40) {
      cycle(this);
    }
  }).on('input', function(e) {
    //this event happens whenever the value changes
    clearTimeout(inputTimer);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" min="1" max="12" value="12" />

Working DEMO

The issue I have is that I can't find a way to detect if the arrow spinners in the input have been clicked, or just the input as a whole has been clicked. Right now it has an issue where it changes the value when you click anywhere in the field when the value is currently at 1 or 12

Is there a way to detect if the click event occurs on the spinners/arrows within the text field?

like image 923
FiniteLooper Avatar asked Dec 03 '15 17:12

FiniteLooper


Video Answer


1 Answers

You have to handle the input event, like this:

$('[type=number]').on('input',function(){
  this.value %= 12 ;
  if( this.value < 1 )
    this.value -= -12 ;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=number>
like image 137
GetFree Avatar answered Oct 12 '22 23:10

GetFree