简体   繁体   中英

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. I know that ProcessField function works fine - tested it using an inline call. But now I want to attach the event via JavaScript. Below is my JavaScript code:

<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. 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.

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. 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.

In order to function for your purposes, you'll have to change the form's action of course. 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.

1) 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

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. I added the eventListener to the form and then used stopPropagation(); to prevent any unintentional triggering during the bubbling phase.

2) Keyword "this" in processField function comes up undefined. 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.

See explanation above concerning the typo of 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 . If you want to cater to that 1% just apply attachEvent as you did in your code.

Let me know if the demo does not work for you before you downvote. Good luck. ;-)

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

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