Hoser
Hoser

Reputation: 5044

Detect if input type 'number' was increased or decreased from previous value

Is there a good way to do this? Can you send the original value as well as the new value to jquery/javascript function? Keeping the old value in some global variable just feels a little messy.

EDIT: Context code

<input type='number' onchange='foo(...)'>

...

<script type=text/javascript>
function foo(...){
    if(old > new){
        alert('decreased');
    }else{
        alert('increased');
    }
}
</text>

Upvotes: 2

Views: 5111

Answers (1)

David Thomas
David Thomas

Reputation: 253328

So don't keep it in a global variable:

<input type="number" value="5" />

$('input[type="number"]').change(function () {
    if (this.getAttribute('value') === this.value) {
        // setting the original 'lastvalue' data property
        $(this).data('lastvalue', this.value);
    } else {
        // take whatever action you require here:
        console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
        // update the lastvalue data property here:
        $(this).data('lastvalue', this.value);
    }
}).change();

JS Fiddle demo.

You could also, in place of this.getAttribute('value') === this.value use instead this.defaultValue === this.value (as in this JS Fiddle demo), this.defaultValue being the original value of the element on DOM-ready.

References:

Upvotes: 5

Related Questions