简体   繁体   中英

Javascript setting value of textbox by function, without getting reset

My goal is to have a text box and a button. If I enter "Hello" in the text box and press the submit button I would like to have see the text box filled with "World.

For the moment the value of the text box will be changed betweeen the

<html>
   <body>
         <script>
            function validateForm() {
                var x = document.forms["myForm"]["Input"].value;
                if (x == "Hello") {
                    alert("test");
                    document.getElementById("Input").value = "World";
                    alert("test2");
                }
            }
        </script>

        <form name="myForm" action="test.html" onsubmit="return validateForm()" method="post">
        Input: <input type="text" id="Input"><br>
        <input type="submit" value="Submit">
        </form>

   </body>
</html>

The problem is that the form gets submitted right after the validation. So you are redirected to test.html again.

If you don't want that to happen, add event.preventDefault(); to your Event Handler ( check out the fiddle to see it working):

<html>
   <body>
         <script>
            function validateForm(event) {
                event.preventDefault();

                var x = document.forms["myForm"]["Input"].value;
                if (x == "Hello") {
                    alert("test");
                    document.getElementById("Input").value = "World";
                    alert("test2");
                }
            }
        </script>

        <form name="myForm" action="test.html" onsubmit="return validateForm(event)" method="post">
        Input: <input type="text" id="Input"><br>
        <input type="submit" value="Submit">
        </form>

   </body>
</html>

You can learn more about event.preventDefault() at MDN .

Just as a sidenote: It is generally better to use addEventListener instead of the onsubmit attribute (Better separation of concerns, you can add multiple event listeners, etc.).

When you submit your page, then the content in the action page will be loaded.

In your case test.html will be loaded.

If you want the value "World" to be shown in the text box on hitting the submit, then return false on your validateForm() method.

Use return false; to stay on the same page and stop form submission.

function validateForm() {
    var x = document.forms["myForm"]["Input"].value;
    if (x == "Hello") {
        document.getElementById("Input").value = "World";
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM