Include empty value fields in jQuery .serialize()
I am trying to submit a form via开发者_如何学JAVA jQuery $.post and serialize the form data via
$('form').serialize();
Unfortunately fields with unchecked radiobutton or checkboxes are not being serialized, ergo submitted.
Is there a way to include ALL fields regardless of whether they contain a value or not?
I guess this only affects fields like this
<input type="checkbox" name="some_name[]" value="1" />
<input type="checkbox" name="some_name[]" value="2" />
Make your own version of serialize :
(function( $ ){
$.fn.mySerialize = function() {
var returning = '';
$('input, textarea',this).each(function(){
var name = this.name;
var value = this.value;
returning += name + '=' + value + '&';
})
return returning;
};
})( jQuery );
$('form').mySerialize();
Fiddle: http://jsfiddle.net/maniator/apGC3/
You seem to be mistaken as shown in this live demo. The foo
field is included even if it doesn't contain any value:
<form>
<input type="text" name="foo" />
<input type="text" name="bar" value="baz" />
</form>
and then:
alert($('form').serialize());
prints (as expected):
foo=&bar=baz
DEMO: http://sandbox.phpcode.eu/g/bbfdd/2
result: bar=
<form>
<input name="bar" />
</form>
<script>
$(function(){
$("input").click(function(){
alert($("form").serialize());
});
});
</script>
精彩评论