JQuery keyup prevents text highlighting in Chrome. How to solve?

I have a function that converts text to uppercase on keyup . The code looks like this (I think I found it on SO too):

 $(selector).bind('keyup', function (e) { if (e.which >= 97 && e.which <= 122) { var newKey = e.which - 32; e.keyCode = newKey; e.charCode = newKey; } $(this).val((object.val()).toUpperCase()); }); 

Problem

In Chrome, when I type text and then try to select it with shift + home , the cursor returns to the last char without selecting anything.

I also tested in Firefox and IE and it works fine.

Please help me

+4
source share
2 answers

One possible solution is not to change the value for each keyboard, but only when the value really changes:

 $('#input').bind('keyup', function(e) { if (e.which >= 97 && e.which <= 122) { var newKey = e.which - 32; e.keyCode = newKey; e.charCode = newKey; } var oldVal = $(this).val(); var newVal = oldVal.toUpperCase(); if(oldVal != newVal) { $(this).val(newVal); } });​ 

Take a look at JSFIDDLE .

+2
source

There is a good solution using only css here:

http://jsfiddle.net/46jrg/

just apply

 text-transform: uppercase 

into the text input area, and then you don’t need to worry about this complicated javascript material. Less code means less mistakes! :)

EDIT: when you select and copy the text, it will still be capitalized, but if you send it to the server, you will either have to paste it before sending, or display it when it gets there. This is usually not a big deal. Most common server languages ​​can do this with a single method call.

Java has String::toUpperCase

PHP has a strtoupper function

Python has String::upper

Ruby has String::upcase

Perl has a uc function

Javascript has String::toUpperCase

C # .NET / VB.NET has String::ToUpper

+2
source

Source: https://habr.com/ru/post/1437712/


All Articles