开发者

Why addEventListener for form submit doesn't work?

Im getting hard to dealing with addEventListener "submit" to form. Here is the script:

<html>
    <head>
        <title>Testing Hehe</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="q" onclick="this.parentNode.submit();" />
            <input type="submit" value="Testing" />
        </form>
        <script type="text/javascript">
            console.log(document.re开发者_StackOverflow社区adyState);
            window.onload = function(){
                console.log(document.readyState);
                document.forms[0].addEventListener('submit',function(e){
                    e.preventDefault();
                },false);

                var form = document.createElement('form');
                    form.method= "post";
                var input= document.createElement('input');
                    input.type = "text";
                    input.name = "test";
                    input.addEventListener('click',function(){
                    form.submit();
                    },false);
                form.appendChild(input);
                var input2= document.createElement('input');
                    input2.type = "submit";
                    input2.name = "sbt";
                form.appendChild(input2);
                form.addEventListener('submit',function(e){
                    alert("test");
                    e.preventDefault();
                },false);
                document.body.appendChild(form);
            }
        </script>
    </body>
</html>

<?php
if($_POST){
    print_r($_POST); 
    exit;
}
?>

From above script, I have succeded kill form submit event when submit button clicked, but when I change the submit trigger to other part, such as when textbox clicked, the "submit" event still post directly. I don't understand why it is happened and how to fix this problem..

Thank you for attention :-) And you r answer will be great for me :-)


Instead of using:

input.addEventListener('click',function(){
                    form.submit();
                    },false);

You could use:

input.addEventListener('click',function(){
                    input2.click();
                    },false);

Just make sure to move var input2= document.createElement('input'); before it.

Example: http://jsfiddle.net/niklasvh/wcpx4/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜