Problem turning input text into uppercase letters

Asked

Viewed 6,239 times

4

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

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 fix it:

When I have a 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 like "RIO D JANEIROE". Note that the first letter is in the correct place and then the cursor is moved to the end.

How can I fix 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">

  • the "problem" is the event you are using; when converting the characters to uppercase the cursor goes to the end. You could change the event to the focusout, for example. Yes, it would be a gambiarra :P

2 answers

7


Solutions with value.toUpperCase seem to have a problem that when typing in the field the cursor is reset, this solution alternative treats 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: https://stackoverflow.com/a/45067218/7558069

An alternative is the solution with CSS:

It has only one visual effect, that is, the change will not persist in the POST.

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

4

Try following the example below, changing the event on for change, I believe that this will work as intended:

$("#texto").change(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">

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

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

  • I need the field to be capitalized all the time, because this field also performs a search as you type

  • 1

    @Joaopaulo Check the second possibility I posted above using only css, I think that solves the problem.

  • 1

    @Leandro a do css is top..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.