Internet Explorer issue with HTML5 form attribute for button element

Viewed 20096

in HTML5, there is the form attribute. Basically

<form id="myform" method="get" action="something.jsp">
    <input type="text" name="name" />
</form>
<input type="submit" form="myform" />

the above code is not working in IE. Can any one help me how to solve this requirement.

I've used the following javascript and jQuery to submit the form, but I facing the Ajax issue. where my page is reloading.

document.getElementById("myForm").submit();

$("#myForm").submit();

How can I submit my form where my page should not load. I am using Anguler JS Ajax.

6 Answers

From @Voldemaras Birškys' answer, I've improved his script to work as a polyfill so you can still have the form attribute no your button and it will work as if EDGE/IE would respect the form attribute.

<form id="form-any-name">
   <input type="button" value="Submit" class="myButton" />
</form>
<button type="submit" form="form-any-name">Submit</button>

<script type="text/javascript">
$(document).ready(function() {
    $('button[type=\'submit\']').click(function (e) {
        var formId = $(e.target).attr("form");
        $("form[id*="+formId+"]").submit();
    });
});
</script>

The main difference is that now we include form on the external submit button. Also, inside the click handler I just use the event to get the target element and from id discover the id of the target form.

:)

If you send form via ajax and use vanilla js, you can add inputs with "form" attribute like below:

function sendViaAjax(event, callback) {
    event.preventDefault();
    var form = event.target;
    var formId = form.id;
    var url = form.getAttribute('action');
    var method = form.getAttribute('method');
    var data = new FormData(form);
    if(isInternetExplorer() && formId) {
        var formInputs = document.querySelectorAll('input[form="'+formId+'"], textarea[form="'+formId+'"], select[form="'+formId+'"]');
        [].forEach.call(formInputs, function (el) {
            var inputName = el.getAttribute('name');
            data.append(inputName, el.value);
        });
    }
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
        // something
    };
    xhr.onerror = function () {
       // something
    };
    xhr.send(data);
}

function isInternetExplorer() {
    return (navigator.appName == 'Microsoft Internet Explorer' ||
        !!(navigator.userAgent.match(/Trident/) ||
            navigator.userAgent.match(/rv:11/)) ||
        (typeof $.browser !== "undefined" && $.browser.msie == 1));
}
Related