javascript - Detect if input type 'number' was increased or decreased from previous value - Stack Overflow

Is there a good way to do this? Can you send the original value as well as the new value to jqueryjava

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().

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745462284a4628762.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信