Search code examples
javascriptinnerhtml

Javascript - Trying to use innerHTML but won't text only changes for a split second


I am new to Javascript and just want to do a simple validation on the username textbox on the below form.

If the username textbox is empty, I want it to print out "Empty" in the span that is next to the textbox when the submit button is clicked. I can get it to do this using the code below but the text only displays for a split second then disappears. Any ideas on how to keep the text there?

<form>
    Username: <input type="text" id="username"><span id="val"></span>
    <input type="submit" onclick="check();">
</form>

<script type="text/javascript">

    function check() {
        var username = document.getElementById("username").value;

        if(username == ""){
            document.getElementById("val").innerHTML = "Empty";
        } else {
            document.getElementById("val").innerHTML = "Full";

        }
    }



</script>

Solution

  • The reason the text isn't staying there is because once you click the button it runs the onclick method, but still submits the form. This pretty much resets the form. If you don't want the form to get submitted and reset then you have to stop the form submission as well. If you add a "return false;" line to the javascript method it should stop the form submission and make the text stay.

    <form>
        Username: <input type="text" id="username"><span id="val"></span>
        <input type="submit" onclick="return check();">
    </form>
    
    <script type="text/javascript">
    
        function check() {
            var username = document.getElementById("username").value;
    
            if(username == ""){
                document.getElementById("val").innerHTML = "Empty";
            } else {
                document.getElementById("val").innerHTML = "Full";
    
            }
            return false;
        }
    </script>