简体   繁体   English

使用addEventListener将JavaScript添加到表单时出现问题

[英]Issue adding javascript to a form using addEventListener

I have a form: 我有一个表格:

 <form method="post" name="Form1" action="default.asp" onsubmit="return processField();">

    <input type="hidden" name="hiddentext1">


    <input type="text" name="text1">
    <input type="submit" value="Submit" id="button1">
</form>

And what I want is to call ProcessField function on the submit of the form. 我想要的是在表单提交时调用ProcessField函数。 I know that ProcessField function works fine - tested it using an inline call. 我知道ProcessField函数可以正常工作-使用内联调用对其进行了测试。 But now I want to attach the event via JavaScript. 但是现在我想通过JavaScript附加事件。 Below is my JavaScript code: 以下是我的JavaScript代码:

<script type="text/javascript">
if (window.addEventListener){
        window.addEventListener('load', attachFormSubmit, false);
} else if (window.attachEvent){
        window.attachEvent('onload', attachFormSubmit );
}

function attachFormSubmit(){
    theForm = document.getElementById("Form1");
    alert("attaching form submit");
    if (theForm.addEventListener){          
            theForm.addEventListener('submit', CleanUpEID, false);
        } else if (theForm.attachEvent){            
            theForm.attachEvent('onsubmit', CleanUpEID);
        }

}

function ProcessField()
{
    alert("processing field");

    if (this.text1.value == '') 
    {
        alert ("Please enter the value")
        this.text1.focus()
        return false
    }

    this.hiddentext1.value = this.text1.value;

    // Disable button
    with ($('button1')) {
        value = "Processing ...";
        disabled = true;
    }


    return true;    
}   

</script>

I have two issues with the above script: 上面的脚本有两个问题:

  • it attaches the event to the form multiple times - every time page reloads. 它将事件多次附加到表单-每次重新加载页面时。 I suspect there is a better place for my code but cannot figure it out. 我怀疑我的代码有一个更好的地方,但无法弄清楚。

  • Keyword "this" in processField function comes up undefined. processField函数中的关键字“ this”未定义。 It works fine if I replace "this" with form name, but I was wondering what needs to be done in order for keyword "this" to work in this case. 如果我用表单名称替换“ this”,效果很好,但是我想知道在这种情况下,需要什么才能使关键字“ this”起作用。

I'd really appreciate if someone could point me in the right direction. 如果有人能指出我正确的方向,我将不胜感激。 Thanks. 谢谢。

EDIT 编辑

OP had a series of questions that involve some fundamental concepts of JavaScript. OP有一系列涉及JavaScript基本概念的问题。 I have provided some links that will hopefully answer those questions. 我提供了一些链接,希望可以回答这些问题。 See the end of this post. 请参阅这篇文章的结尾。

Rewrote the code to demonstrate it actually works with a test server . 重新编写代码以证明它可以在测试服务器上正常工作。 With the syntax errors, you'd never get it working. 由于语法错误,您将永远无法正常工作。 The biggest error is you call processField() but you define a function called ProcessField() , JavaScript is case-sensitive. 最大的错误是您调用processField()但定义了一个名为ProcessField()的函数,JavaScript区分大小写。

In order to function for your purposes, you'll have to change the form's action of course. 为了实现您的目的,您当然必须更改表单的action I had to validate it's input for a min of 5 and a max of 15 alphanumerics due to the test server's limits, so you'll want to change that as well probably. 由于测试服务器的限制,我必须验证其输入的最小值为5,最多为15个字母数字,因此您可能也希望更改它。

1) it attaches the event to the form multiple times - every time page reloads. 1)它将事件多次附加到表单-每次重新加载页面时。 I suspect there is a better place for my code but cannot figure it out 我怀疑我的代码有更好的地方,但无法弄清楚

You are adding/attaching the eventListener/Handler to the window which makes your submit event global, plus you didn't provision any way to prevent default behavior, so any form and form elements that by default are triggered by a submit event will popup on the event chain. 您正在将eventListener / Handler添加/附加到使您的提交事件变为全局的窗口中,并且您没有提供任何防止默认行为的方法,因此默认情况下,由Submit事件触发的任何表单和表单元素都会弹出事件链。 I added the eventListener to the form and then used stopPropagation(); 我将eventListener添加到窗体中,然后使用stopPropagation(); ;。 to prevent any unintentional triggering during the bubbling phase. 以防止在冒泡阶段发生任何意外触发。

2) Keyword "this" in processField function comes up undefined. 2)processField函数中的关键字“ this”出现未定义。 It works fine if I replace "this" with form name, but I was wondering what needs to be done in order for keywrod "this" to work in this case. 如果将“ this”替换为表单名称,效果很好,但是我想知道在这种情况下,需要什么才能使键盘输入“ this”起作用。

See explanation above concerning the typo of processField .* 请参阅上面有关processField错字的说明。*

Btw, I didn't bother adding the cross-browser crap attachEvent because IE8 is dead, and that 1% of the world can use IE9 . 顺便说一句,我没有添加跨浏览器废话attachEvent麻烦, 因为IE8已死,并且全世界有1%的人可以使用IE9 If you want to cater to that 1% just apply attachEvent as you did in your code. 如果您想迎合1%的需求,只需像在代码中那样应用attachEvent

Let me know if the demo does not work for you before you downvote. 让我知道演示是否对您不利,然后再投票。 Good luck. 祝好运。 ;-) ;-)

http://glpjt.s3.amazonaws.com/so/34775593.html http://glpjt.s3.amazonaws.com/so/34775593.html

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>34775593</title>
</head>

<body>


    <form method="post" id="Form1" name="Form1" action="http://www.hashemian.com/tools/form-post-tester.php/so_post">

        <input type="hidden" id="hiddentext1" name="hiddentext1">


        <input type="text" name="text1" id="text1" placeholder="Submit 5 to 15 alphanumerics">
        <input type="submit" value="Submit" id="button1">
    </form>
    <p>Once post is submited, server's response is returned with value of #hiddentext1 and #text1</p>
    <div class="serverData">
        <a href="http://www.hashemian.com/tools/form-post-tester.php/data.php/so_post">Server-side Results</a>
    </div>

    <script>
        var form = document.getElementById('Form1');
        var htxt = document.getElementById('hiddentext1');
        var btn = document.getElementById('button1');

        form.addEventListener('submit', processField, false);

        function processField(e) {

            var txt = document.getElementById('text1');
            var str = txt.value;
            var alnum = str.length;
            alert("processing field");

            if (alnum < 5 || alnum > 15) {
                alert("Please enter a value of 5 to 15 alphanumeric values ");
                txt.focus();
                return false;
            }

            htxt.value = str;

            // Disable button
            this.setAttribute('disabled', true);
            this.value = "Processing ...";

            e.stopPropagation();
        }
    </script>
</body>

</html>

References 参考文献

addEventListener()

Bubbling & capturing 冒泡和捕获

Loading 载入中

<script>

Getting elements 获取元素

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

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