admin管理员组

文章数量:1426033

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>

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>
Share Improve this question edited Oct 7, 2013 at 19:23 Hoser asked Oct 7, 2013 at 19:17 HoserHoser 5,0449 gold badges49 silver badges68 bronze badges 2
  • Can we see some context code? – Steve Commented Oct 7, 2013 at 19:19
  • 1 You're going to have to keep the old value around, and in scope. If you're working in the global space, then you'll have to store it globally. You may consider wrapping the code so it doesn't pollute the global space though . . . – Julio Commented Oct 7, 2013 at 19:24
Add a ment  | 

1 Answer 1

Reset to default 5

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:

  • change().
  • data().

本文标签: javascriptDetect if input type 39number39 was increased or decreased from previous valueStack Overflow