最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery keyup only keys that affects textarea content - Stack Overflow

programmeradmin2浏览0评论

How can I detect if the value of a textarea changes using jQuery? I'm currently using keyup() but this triggers every key stroke of course, I dont want my code to run if it's an arrow key that was pressed or any other key that doesn't have an impact on the value of the textarea.

Take a look:

$('textarea').keyup(function() {
     if (content was changed)
         // Do something
});

I hope you understand. How can I do this the best way? I don't want to pare the current value to an old value to check for changes, I hope that's not the only way.

How can I detect if the value of a textarea changes using jQuery? I'm currently using keyup() but this triggers every key stroke of course, I dont want my code to run if it's an arrow key that was pressed or any other key that doesn't have an impact on the value of the textarea.

Take a look:

$('textarea').keyup(function() {
     if (content was changed)
         // Do something
});

I hope you understand. How can I do this the best way? I don't want to pare the current value to an old value to check for changes, I hope that's not the only way.

Share Improve this question asked Feb 12, 2013 at 11:18 lawlslawls 1,5183 gold badges21 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

By all means the easiest way is to store old values to data and do the check every keyup. The solution is quite short and will work in any case. No need to reinvent the wheel.

$("textarea").data("oldValue", function() {
    return this.value;
}).keyup(function() {
    var $this = $(this);
    if (this.value !== $this.data("oldValue")) {
        // Do something

        $this.data("oldValue", this.value);
    }
});

DEMO: http://jsfiddle/vvbSj/

$('textarea').blur(function() {
  //This will be invoked when the focus is removed
});

$('textarea').change(function() {
  //Same as the blur
});

Is this what you want

发布评论

评论列表(0)

  1. 暂无评论