简体   繁体   English

HTML表单提交未显示javascript输出

[英]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. 单击Action2按钮的效果与我预期的一样,但是单击“ Action1”按钮将刷新页面,并且action1的输出消失。

Why is there a refresh, and how can I show the output of action1? 为什么要刷新,如何显示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; 你可以写return false; in your onsubmit handler to prevent the usual action, ie form submission. 在您的onsubmit处理程序中,以防止执行常规操作,即表单提交。 Then the page shouldn't "refresh". 然后,该页面不应“刷新”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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