HTML Forms Text onkeyup
-
08-10-2019 - |
Question
This code changes whatever the user types in the box to uppercase, and displays the result in the box.
<html>
<head>
<script type="text/javascript">
function upperCase(x)
{
var y=document.getElementById(x).value;
document.getElementById(x).value=y.toUpperCase();
document.getElementById("mySpan").value=y.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onkeyup="upperCase(this.id)">
<br/>
<span id="mySpan"></span>
</body> </html>
But how can I make it so that it displays it UNDER the text box? And that when the user types, the upper case text is displayed under the text box?
Thanks!
Solution
I would suggest the following, more maintainable approach, which uses the event registration model as opposed to the inline model:
JS:
<script>
document.getElementById("fname").onkeyup = function() {
document.getElementById("mySpan").innerHTML = this.value.toUpperCase();
}
</script>
Markup:
Enter your name: <input type="text" id="fname"/>
<br/>
<span id="mySpan"></span>
OTHER TIPS
Create a css class
.showUpperCase { text-format: uppercase; }
and add this to your span or textBox.
<span id="mySpan" class="showUpperCase"></span>
This doesn't change the characters entered, only shows them as upper-case. That means that if you're handling input via a textBox, you'll have to change to upper-case server-side as well. This is not an additional chore, since you have to be wary of client-side handling and da a server-side verification, regardless of what the client does