Nameo0
Nameo0

Reputation: 81

Javascript changing HTML but change then immediately defaults back to the hard-coded value

I am trying to make it so that when I hit the submit button in html, we value in the input field replaces the item inside of the P element that has the id "numberz".

I can get the code to do that but the website immediately changes back to having the default value in the P element with the id "numberz".

How do I prevent the website from changing back to the default value of the element that is hard-coded into the HTML file?

<!DOCTYPE html>

<html>
    <head>
        <title>JS test</title>
        <script>
            function e() {
                var x = document.getElementById("numberz");
                var z = document.getElementById("num").value;
                //alert(x.innerHTML + " s " + z);//
                x.innerHTML= z;
            };
        </script>
    </head>
    <body>
        <p>The number is:</p>
        <p id = "numberz">s</p>
        <br>
        <br>
        <form onsubmit = "return e();">
            <input id = "num" type = "text" size = "4" placeholder = "test"/>
            <input type = "submit" value = "Submit"/>
        </form>
    </body>
</html>

Upvotes: 1

Views: 1538

Answers (1)

epascarello
epascarello

Reputation: 207511

Because the form is submitting, you need to cancel the form submission.

        function e() {
            var x = document.getElementById("numberz");
            var z = document.getElementById("num").value;
            //alert(x.innerHTML + " s " + z);//
            x.innerHTML= z;
            return false;
        };

Upvotes: 5

Related Questions