7

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.

kowalcyck
  • 103
  • 3
  • 11

3 Answers3

12

True, because when function is called the field is not updated with the value

The event is called in this steps

  1. Keydown
  2. Keypress
  3. updateview
  4. Keypress
  5. updateview
  6. keyup

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;
});
Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52
6

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/>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
3

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" />
Community
  • 1
  • 1
lshettyl
  • 8,166
  • 4
  • 25
  • 31