开发者

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 acti开发者_StackOverflowon.

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, i.e. form submission. Then the page shouldn't "refresh".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜