开发者

How can a javascript function be fired when a user types text into an input field or pastes text into it?

$(document).ready(function() {
 $("input[id^='question']").开发者_JAVA技巧live('keyup',function(ev){
    id=this.id.substr(8);
    if (ajaxCallTimeoutID != null)
    clearTimeout(ajaxCallTimeoutID);
ajaxCallTimeoutID = setTimeout(function(){subjectivecheck(id)}, 1000);
}); 
});

There is a problem. When a user pastes text into an input field, the function above can not be fired. How to solve this problem?


The onchange event is what you want here. It fires when the textbox loses focus (blur) and has had its value changed since it received focus. It takes care of the paste problem.

So instead of .live('keyup', use live('change'.

This is as good as it gets, without using some ridiculous interval polling. And just for the purpose of context, be aware that any user can disable Javascript in the browser whenever they feel like it.


The Paste (onpaste) event is not standard - it is AFAIK supported only in Internet Explorer (see: http://msdn.microsoft.com/en-us/library/ms536955(VS.85).aspx)

The change (onchange handlder) event is standard - but that will only fire if the value of the textbox changed in the time between gaining and losing focus - i.o.w. detecting change requires the textbox to lose focus.

What you could do, is use setInterval() (http://www.w3schools.com/jsref/met_win_setinterval.asp) to poll the value of the textbox, and compare it with the previous value.


At the onfocus event on the field, you can start a timer to check if the field value has changed.

And at onblur, clear that timer.

The paste with ctrl+v is ok with onkeyup, but not with the mouse right click or with a browser undo.


That's not the only problem. Even if you could catch cut and paste reliably on all browsers, which you can't, there are still more ways of putting content in a form field. For example on some platforms dragging a file to an input will put the pathname in, with no event for you to catch. Or a user might do right-click-Undo to change the contents. Or Delete. Or select some text from the input or another input and drag-and-drop it in. And probably many more I haven't thought of.

If you want to be informed of all changes to a form field more quickly than onchange, I'm afraid there is no alternative but to constantly monitor the value of the element in a polling setInterval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜