开发者

How can I get the new value of a HTML text element in a key event handler, also for special keys?

Lets suppose we have a html text input element and it has text "abc" and cursor is between "b" and "c". If we press backspace key then how can we get the value "ac"?

Please note that in case of special keys KeyPress event do not fire. The only events that fire are KeyDown and KeyUp and none of them has the value after the effect of special key is applied. The effect is visible after the eventhandlers of these events exit but since we have only these two events we have to somehow get the affected/latest value inside these events.

We can go to a complex way by manually applying the effect ourselves but its very very complicated given the facts that we have to find the cursor position, write different code for different special keys and bring browser compatibility. The browser, whichever it is, is already applying the effect once the eventhandlers exit but is there some way to get that latest value in those events without manually applying it or in some other event?

Please note that I am not searching 开发者_运维技巧for "how to find which key is pressed". I can find that by looking at the event object inside the KeyDown or KeyUp event handlers. I want to apply the effect of the special key without using a lot of manual code.

I have already looked at Capturing HTML Text Input Key press after key has been applied?. Its talking about a different thing than my question.

My ultimate task is to have a web page with only two controls: a textbox and a button. The button is initially disabled. User can type in textbox and on every key its checked that there is some text in the textbox, if there is then button is enabled, if not then button is disabled. The difficult part is to take into consideration special keys such as delete, enter, tab, backspace.

Note: I do not want to work on the blur eventhandler of the HTML text element because it affects the tab order.


Example using jQuery. The target value is stored on the title attribute, but you could make this an ajax request, or whatever logic you need. In the following case, typing 'abc' in the text box will make the go button enabled.

HTML:

<input type="text" title="abc" id="in">
<input type="button" id="go" value="Go" disabled="disabled">

Javascript:

$("#in").keyup(function() {
    if($(this).val() == $(this).attr("title")) {
        $("#go").removeAttr("disabled");   
    }
});

JSFiddle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜