If you would like to check for the form
attribute without using an external plugin or library you could try the following:
Change:
if ($.browser.msie) {
To:
if ($("#extra")[0].form === null) {
See document.getElementById vs jQuery $() for more information on why $("#extra")[0]
is used.
Resulting in:
$('#myform').on('submit', function (e) {
var query = $(this).serialize();
if ($("#extra")[0].form === null) {
//fixed form attribute not supported in IE
var extra = $('[form=myform]').each(function () {
if (/(=)\w*/gi.test(query)) query += '&';
query += this.name + '=' + this.value;
});
}
console.log(query);
return false;
});
JS Fiddle:
http://jsfiddle.net/ezq9mu1a/1/
As far as I am aware this is the sort of check that Modernizr does (although I think it dynamically creates the input to test on). Running this fiddle in IE triggers the fallback code while Safari, Chrome, Firefox and Opera just use serialize
.
EDIT
As we can't rely on an existing element in the page we will need to create a test form
and input
for the purposes of checking if the form
attribute is supported. To do this we can modify the code in the following way:
Add:
//Create test elements and amend them to the DOM
var testForm = $('<form />', { 'id': "testForm" })[0];
var testInput = $('<input />', { 'form': "testForm" })[0];
$('body').append(testForm, testInput);
//Set a variable to store whether the form attribute is supported
var formSupported = (testInput.form !== null) ? true : false;
//Remove the test elements from the DOM
$(testForm).remove();
$(testInput).remove();
Change:
if ($("#extra")[0].form === null) {
To:
if (!formSupported) {
Resulting in:
//Create test elements and amend them to the DOM
var testForm = $('<form />', { 'id': "testForm" })[0];
var testInput = $('<input />', { 'form': "testForm" })[0];
$('body').append(testForm, testInput);
//Set a variable to store whether the form attribute is supported
var formSupported = (testInput.form !== null) ? true : false;
//Remove the test elements from the DOM
$(testForm).remove();
$(testInput).remove();
if (!formSupported) {
$("#formSupported").html("No");
}
$('#myform').on('submit', function (e) {
var query = $(this).serialize();
if (!formSupported) {
//fixed form attribute not supported in IE
var extra = $('[form=myform]').each(function () {
if (/(=)\w*/gi.test(query)) query += '&';
query += this.name + '=' + this.value;
});
}
console.log(query);
return false;
});
JS Fiddle:
http://jsfiddle.net/ezq9mu1a/3/