I made this code:
$(".SermeCoopConvertirMayuscula").keypress(function (e) {
$(this).val($(this).val().toUpperCase());
regexp = /^[A-Z0-9 ]*$/;
return regexp.test($(this).val());
});
It is working fine. But when i type something it doesn't update my last inserted character. How can i make that the last character is added?
I need use the keypress event, i cant use the keyup event.
Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.
The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.
True, because when function is called the field is not updated with the value
The event is called in this steps
So if you can change this event to keyup then you will get the latest value
Or, if you still want to use keypress event that you can do one thing you can use the following code
$(".SermeCoopConvertirMayuscula").keypress(function (eventObject) {
var val = $(this).val() + eventObject.key;
val =val.toUpperCase()
var regexp1 = /^[A-Z0-9 ]*$/;
var regexp2 = /^[A-Za-z0-9 ]$/;
if(regexp1.test(val) && regexp2.test(eventObject.key)) {
$(this).val(val);
}
return false;
});
Use keyup() instead. when keypress()
is fired, the most recent character is still not registered in the input, so $(this).val()
will not include it for the most recent event
$("input").keyup(function (e) {
$(this).val($(this).val().toUpperCase());
regexp = /^[A-Z0-9 ]*$/;
return regexp.test($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input/>
You could also try input
which also takes care of various other input scenarios. Take a look at this for more details.
$(".SermeCoopConvertirMayuscula").on("input", function (e) {
$(this).val($(this).val().toUpperCase());
regexp = /^[A-Z0-9 ]*$/;
return regexp.test($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="SermeCoopConvertirMayuscula" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With