Problem converting input text to capital letters

2

I have input and I want it to only allow capital letters in real time.

This code seems to work perfectly.

$("#texto").on("input", function(){
    $(this).val($(this).val().toUpperCase());
});

But I noticed a bug and I do not know how to solve it:

When I have text for example "RIO JANEIRO" and I want to correct it for "RIO DE JANEIRO", when I type any letter in the middle of the word the input cursor is reset and goes to the last character and then the text is thus "RIO D JANEIROE". Notice that the first letter is in the correct place and then the cursor is moved to the end.

How can I resolve this?

$("#texto").on("input", function(){

	$(this).val($(this).val().toUpperCase());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="texto">
    
asked by anonymous 06.04.2018 / 15:10

2 answers

3

Solutions with value.toUpperCase seem to have a problem that when typing in the field the cursor is reset, this solution alternative addresses this problem:

function handleInput(e) {
   var ss = e.target.selectionStart;
   var se = e.target.selectionEnd;
   e.target.value = e.target.value.toUpperCase();
   e.target.selectionStart = ss;
   e.target.selectionEnd = se;
}
<input type="text" id="txtTest" oninput="handleInput(event)" />
Source: link

An alternative is the CSS solution:

It only has a visual effect, meaning the change will not persist in POST .

#InputUpper {
  text-transform:uppercase
}
<input type="text" name="InputUpper" id="InputUpper" value="teste" />
    
06.04.2018 / 15:34
3

Try to do the following example by changing the event on to change , I believe it works the way you want it to:

$("#texto").change(function(){

	$(this).val($(this).val().toUpperCase());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="texto">

Another possibility would be with css using the property text-transform: uppercase , hence typing the text will already be in uppercase:

<input type="text" id="texto" style="text-transform: uppercase;"/>
    
06.04.2018 / 15:15