elepil
asked on
JavaScript keypress issues
The following is simply trying to filter the characters the user can input. There are two issues:
1) For some reason, when I try to get the val() of the text field through jQuery, the value I'm getting back is one character behind. For example, if I type in 'a', the value I get back is an empty string. When I type a 'b' so that the value should now be 'ab', I get only 'a', and so on.
2) When I press backspace, the keypress event is not firing. It's important that I be able to detect that, too.
Can anyone tell me why this is behaving this way? And what can I do rectify it? Thanks.
1) For some reason, when I try to get the val() of the text field through jQuery, the value I'm getting back is one character behind. For example, if I type in 'a', the value I get back is an empty string. When I type a 'b' so that the value should now be 'ab', I get only 'a', and so on.
2) When I press backspace, the keypress event is not firing. It's important that I be able to detect that, too.
Can anyone tell me why this is behaving this way? And what can I do rectify it? Thanks.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function() {
var sAllowableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-',.";
$("#txtText").keypress(function(event) {
var s = String.fromCharCode(event.keyCode);
if (sAllowableCharacters.indexOf(s) === -1) {
return false;
}
console.log($("#txtText").val());
});
});
</script>
<style>
</style>
</head>
<body>
<input id="txtText" />
</body>
</html>
Yep, because it hasn't been inserted yet. Do you need to get the value right at that point? otherwise just have keyup event to capture what the value is
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
For some reason, I always thought I could handle all in just one type of keyboard event. I guess I really need to use multiple events to make this thing work as I want. Thanks for all your help, Rob!