简体   繁体   中英

HTML Form submit not displaying the javascript output

I wish to have a submit button (for the default form action), and an additional button for a second action.

I have the following code:

<html>
<head><title></title>
<?PHP
$Input = "";
if(isset($_POST['Input'])) $Input = $_POST['Input'];
?>
</head>

<body>
    <FORM id ="form1" method="post">
        Input: <INPUT TYPE = "TEXT" VALUE ="<?php echo $Input;?>" NAME = "Input" SIZE="3">
        <INPUT TYPE = "submit" id = "action1" VALUE = "action 1"> 
        <INPUT TYPE = "button" id = "action2" VALUE = "action 2">
    </FORM>
    <br>

    <script type="text/javascript">
        var form = document.getElementById('form1'); 

        form.onsubmit = function() {
            document.getElementById("php_code_action1").innerHTML="<?php echo "action 1<br>"; ?>";
            document.getElementById("php_code_action2").innerHTML="";
        };

        document.getElementById('action2').onclick = function() 
        {     
            document.getElementById("php_code_action2").innerHTML="<?php echo "action 2<br>"; ?>";
            document.getElementById("php_code_action1").innerHTML="";
        } 
    </script>

    <span id="php_code_action1"> </span>
    <span id="php_code_action2"> </span>

</body>
</html>

A click on the Action2 button works as I expect, but a click on "Action1" button has the page refresh and the output of action1 disappear.

Why is there a refresh, and how can I show the output of action1?

form.onsubmit = function() {
    document.getElementById("php_code_action1").innerHTML="<?php echo "action 1<br>"; ?>";
    document.getElementById("php_code_action2").innerHTML="";
    return false;
};

You can write return false; in your onsubmit handler to prevent the usual action, ie form submission. Then the page shouldn't "refresh".

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