I am using the following style attribute to set the user input to uppercase so that when the user starts typing in the text box for example railway
, then it should
Using CSS text-transform: uppercase
does not change the actual input but only changes its look.
If you send the input data to a server it is still going to lowercase or however you entered it. To actually transform the input value you need to add javascript code as below:
document.querySelector("input").addEventListener("input", function(event) {
event.target.value = event.target.value.toLocaleUpperCase()
})
Here I am using toLocaleUpperCase()
to convert input
value to uppercase.
It works fine until you need to edit what you had entered, e.g. if you had entered ABCXYZ and now you try to change it to ABCLMNXYZ, it will become ABCLXYZMN because after every input the cursor jumps to the end.
To overcome this jumping of the cursor, we have to make following changes in our function:
document.querySelector("input").addEventListener("input", function(event) {
var input = event.target;
var start = input.selectionStart;
var end = input.selectionEnd;
input.value = input.value.toLocaleUpperCase();
input.setSelectionRange(start, end);
})
Now everything works as expected, but if you have slow PC you may see text jumping from lowercase to uppercase as you type. If this annoys you, this is the time to use CSS, apply input: {text-transform: uppercase;}
to CSS file and everything will be fine.