How to get the old value of a textarea

扶醉桌前 提交于 2020-01-06 02:35:10

问题


That's it. How can I get the old value of a textarea in order to compare it with a new value?. The current value becomes the old value after triggering an event (say, a keyup event).

I have seen some solutions, for example, using cookies to record the old value and the new value, however, such solution doesn't work in my case because of the type of manipulation I want to perform later.

Hopefully, there is a suggestion which works better than that.

Thanks in advance.

UPDATE:

After following some suggestions from @drachenstern, @Matthew, @Peter, I ended up with something like this

var startTimer = null;
var oldValue;
$("#textarea").keydown($.debounce( 1000, true, function(){
oldValue = $("#textarea").val();
}
));

$("#textarea").keyup(function(){
if(startTimer) clearTimeout(startTimer);
startTimer = setTimeout(function(){
var newValue = $("#textarea").val();
d = // here a clever comparison
oldValue = newValue;
},2000);
})

By the way, $.debounce is a function from the jQuery throttle / debounce plugin.

This does exactly what I want, however, I'd like to obtain the variable d outside of setTimeout function and of keyup function, in order to use it elsewhere. However, clearTimeout seems to be tricky when it comes to return values. Any way to get the value of the d?.


回答1:


var oldValue = document.getElementById("textareaid").value;

document.getElementById("textareaid").onchange = function(){
  var newValue = this.value;
  //Compare oldValue and newValue
  oldValue = newValue;
}


来源:https://stackoverflow.com/questions/5215480/how-to-get-the-old-value-of-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!