简体   繁体   中英

onsubmit function is not being called

I am designin a shoutbox which is AJAX based. http://businessgame.be/shoutbox.php

The script works perfectly in google chrome, but other browsers don't act like I expect.

To shout a new message, there is a form which owns a input text field. When pressing enter, the form is being submitted, so I have omitted a submit button since pressing enter is sufficient.

<form method="POST" action="" onsubmit="javascript: return shout();" enctype="multipart/form-data">
<input type="text" style="width: 100%;" name="txtShout" id="txtShout" maxlength="600" autocomplete="off" title="Shout!" placeholder="Shout!">
</form>

The shout function looks like this:

function shout() {
alert("test");
        // Post shout and clear textField
        if(getLength("txtShout")) {
            AjaxUpdate("./includes/shout.php?message=" + getItemValue("txtShout"), refreshShoutBox);
            setItemValue("txtShout", "");
        }

        // Stop submit
        return false;
    }

Normally, the script should call the shout function, the AJAX would send a request to add the shout and then return false so the form does not get submitted.

But in all browsers except Google Chrome, the form gets submitted anyway. I put in an alert() in the function to check if it was called or a coding mistake but the alert is not being shown.

Well, for some reason, I couldn't get the onsubmit function working in other browsers. Instead of desperately keep looking to fix it a decided to go for a different approach. Now I just added a listener to the text box to check when a key is pressed if it was the enter key and then call that function.

That seemed to work, still had to remove the form though, because otherwise it would get submitted ^^.

So now I got something like this:

function shoutEnterListener() {
    // Get object
    var domObject = document.getElementById("txtShout");

    // Get shoutbox html code
    if(domObject) {
        domObject.onkeydown = shoutEnter;
        domObject.onkeypress = shoutEnter;
    }
}

function shoutEnter(e) {
    var keyCode;

    // Check which key has been pressed
    if (window.event) {
        keyCode = window.event.keyCode;
    } else {
        keyCode = e.which;
    }

    // If enter, shout!
    if (keyCode == 13) {
        shout();
    }
}

The shoutEnterListener() is called in the init function. This also proves that there wasn't a coding error whatsoever but purely the function not being called at all.

If you still find the solution to the previous problem, let me know, because this is a bit tedious and intensive code.

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