8

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.

3
  • Can you not use the api.jquery.com/change function instead? Commented Jun 5, 2015 at 13:50
  • Because I like to see what I'm writing in UpperCase Commented Jun 5, 2015 at 13:55
  • Have a look at my latest solution if you can't use keyup event Commented Jun 5, 2015 at 14:08

3 Answers 3

13

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; }); 
Sign up to request clarification or add additional context in comments.

Comments

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/>

Comments

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" />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.