Javascript form.submit() not working in Firefox

user3120173 picture user3120173 · Jul 10, 2014 · Viewed 29.8k times · Source

There are several questions/answers on this here, here and here and elsewhere, but they all seem JQuery specific and do not appear to apply to this (for example, I am NOT creating a new Form object, this is an existing form in the document. Also I am NOT using Jquery at all).

I have a form which has to be modified before submission for reasons of IE7 compatibility. I have to strip out all the BUTTON tags from my form and then add a hidden field, but this is all in an existing form on the existing HTML page. This code works properly in IE and Chrome but doesn't work in Firefox (versions 23 & 24 both tested).

    buttonClickFunction(formName, buttonObject) {
        var formObject = document.forms[formName];
        var i = 0;

        // Strip out BUTTON objects
        for (i=0;i<formObject.length;i++) {
            if (formObject[i].tagName === 'BUTTON') {
                formObject[i].parentNode.removeChild(formObject[i]);
                i--;
            }
        }

        // Create new field
        var newField = document.createElement('input');
        newField.type = 'hidden';
        newField.id=buttonObject.id;
        newField.name = buttonObject.name;
        if (buttonObject.attributes['value'] != null) {
            newField.value = buttonObject.attributes['value'].value;
        } else {
            newField.value = buttonObject.value;
        }

        // Submit form
        formObject.appendChild(newField);
        document.forms[formName].appendChild(newField);
        document.forms[formName].submit();
    }

In addition to the document.forms[formName].submit() I have also tried formObject.submit() - both work in Chrome but both fail in Firefox. I'm at a loss as to why this doesn't work - I've traced through the JS and watched that document.forms[formName].submit() execute - no exception appears but nothing goes to the server.

Can anyone identify why Firefox won't submit this form, and how I can fix it?

Answer

g00glen00b picture g00glen00b · Jul 11, 2014

Firefox expects that, when you submit a form, you have at least a submit button available, meaning there should be something like:

<button type="submit">Click me</button>

or:

<input type="submit" value="Click me" />

When you use the first one in your code, it will not work (because you strip out all buttons before submitting the form). When you use the second option, it will work, also in Firefox. As you can see in this fiddle: http://jsfiddle.net/q9Dzc/1/