Question:
I have an input
and I want it to only allow capital letters in real time.
This code apparently works perfectly.
$("#texto").on("input", function(){
$(this).val($(this).val().toUpperCase());
});
But I noticed a bug and I don't know how to solve it:
When I have a text for example "RIO JANEIRO" and I want to correct it to "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 looks like this "RIO D JANEIRO". 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>
<input type="text" id="texto">
Answer:
Solutions with value.toUpperCase
seem to have a problem that when typing in the field the cursor is reset, this workaround addresses this issue:
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)" />
Fonte: https://stackoverflow.com/a/45067218/7558069
An alternative is the solution with CSS :
It has a visual effect only, i.e. the change will not persist on POST
.
#InputUpper {
text-transform:uppercase
}
<input type="text" name="InputUpper" id="InputUpper" value="teste" />