Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

javascript - How do I listen for step up event for input type="number"

I want to be able to listen to <input type="number" /> step UP (increment) and step down events with jQuery. (currently I can only understand how to listen to change event)

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For input type="number", you can use the change event, but will possibly have more cases to handle and create some clutter. I broke it down, I recommend using the "mouseup" event for the increment feature (which will mainly be used from pc) But if the user uses a device instead, I would use the event 'keyup' since the increment feature will not appear and the user will have an on-screen keyboard instead. The change event will listen for both.

For example :

$(".counter").bind('mouseup', function () { 

    if($(this).val() == undefined || $(this).val() == "")
            return; /* Exit dont bother with handling this later, if its not needed leave. */

    /* Important Check against integers and not strings. */
    /* Comparing against arrays will give unexecpted behavior, size is different then the value. */         
    var newVal = parseInt($(this).val());
    var oldVal = parseInt($(this).data('old-value'));

    if (oldVal < newVal) {      
        alert('incrementing');
    }
    else{

        alert('decrementing'); 
    }

    $(this).data('old-value', $(this).val());

});

$(".counter").bind('keyup', function () { 
    /* Similar logic */
});

I use "bind" instead of "on" or the by method "change" since "on" is a shorthand for bind.

JSFiddle Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...