Search code examples
javascripthtmlformsonkeyup

HTML Forms Text onkeyup


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>
    

    Demo: http://jsfiddle.net/karim79/GPZ8h/