JSFiddle - React, Tailwind, and code Playground
by mindplay
HTML
<html>
<head>
<title>HTML5 serialize()</title>
</head>
<body>
<form name="a">
<input type="hidden" name="baz" value="789"/>
</form>
<form name="b">
<input type="hidden" name="boo" value="aaaa" form="a"/>
<input type="hidden" name="zoo" value="beee"/>
</form>
<input form="a" name="foo" value="123" type="text"/>
<input name="bar" value="345" type="text"/>
</body>
</html>
JavaScript
/*
This script extends the jQuery.fn.serialize() function,
adding support for form-associated elements - see:
http://www.w3.org/TR/html5/association-of-controls-and-forms.html#form-owner
(note that this is incomplete - it does not attempt to
filter form-associated elements from other forms, although
for some reason this actually seems to work in FF7 and
Chrome, but not in IE9...)
*/
(function(){
var _serialize = jQuery.fn.serialize;
jQuery.fn.serialize = function() {
var $this = $(this);
var form = $this.is('form')
? $this.get(0)
: $this.find('form:first').get(0);
var f = '[form="' + $(form).attr('name') + '"]';
return _serialize.apply($('input'+f+', textarea'+f+', select'+f+', button'+f).add($this));
};
})();
/*
The following test shows that serialize() is capable of
picking up associated elements from outside the form
which is being serialized: form "a" will include the
"boo" element, which is nested in another form ("b"),
as well as the "foo" element, which is located outside
either of the two forms.
*/
console.log($('form[name="a"]').serialize());
console.log($('form[name="b"]').serialize());