javascript onkeypressed not giving current text box content
I have an html form like this:
<form id="boxy" action="layout.html" method="get" accept-charset="utf-8">
<input type="text" id="a" onkeypress="Boxy.Check(this);">
</form>
Invoking javascript like this:
Boxy.Check = function() {
input = document.getElementById(this.currentSelector.id).value;
console.log("\"" + input + "\"");
};
However, this.value
is the previous开发者_C百科 value before onkeypress
.
For example, if I just type "A" into the form, console.log()
prints "". And if I type "AA", console.log
prints "A".
Is there a way to get the current content of the input?
I think you need to use onkeyup.
var KeyID = (window.event) ? event.keyCode : e.keyCode;
values for KeyID are:
> 16 (Shift)
> 17 (Ctrl)
> 18 (Alt)
> 19 (Pause)
> 37 (Left)
> 38 (Up)
> 39 (Right)
> 40 (Down)
This way you can check whether such a key is pressed.
Untested but this should work. Please let me know if something doesn't work as it should.
EDIT: Added cross-browser support
Try using getElementById
<input type="text" id="a" onkeyup="Boxy.Check();">
Boxy.Check = function() {
input = document.getElementById(
document.getElementById('a').currentSelector.id
).value;
console.log("\"" + input + "\"");
};
using PeeHaa's advice with unkeyup
精彩评论