29
votes

(Question updated to reflect real issue)

I just realized that serializeArray is not fetching content from disabled fields.

A set of (street) address fields are populated by selecting an item from a autosuggest list. Once this is done, the fields are disabled. I could change this to read only, but I want the disabled look and feel without having to change CSS.

Is there a way to have serializeArray grab data fro, the disabled fields?

Solution

Thanks to Mohammad, I created a small plugin that helps me solve my issue:

(Fiddle)

    var form_data = $('form').serializeAll();

    (function ($) {
      $.fn.serializeAll = function () {
        var data = $(this).serializeArray();

        $(':disabled[name]', this).each(function () { 
            data.push({ name: this.name, value: $(this).val() });
        });

        return data;
      }
    })(jQuery);
4
do you have name attribute in your dynamically added element'sMohammad Adil
Yes. All input fields that needs to be submitte4d has t he name attribute. Oh, one imporatnt note, the fields are disabled! (sorry - I'll update Q)Steven
That is the reason why serializeArray doesn't pick those element'sMohammad Adil

4 Answers

59
votes

Try this

var data = $('form').serializeAllArray();

And here is the small plugin that is used

(function ($) {
  $.fn.serializeAllArray = function () {
    var obj = {};

    $('input',this).each(function () { 
        obj[this.name] = $(this).val(); 
    });
    return $.param(obj);
  }
})(jQuery);

You can also try enabling all your element's just to serialize them and then disable them after serializing.

var myform = $('#form');
var disabled = myform.find(':input:disabled').removeAttr('disabled');
var serialized = myform.serializeArray();
disabled.attr('disabled','disabled');
19
votes

you can use readonly serializeArray() can read it.

0
votes

This is expected behavior and won't be fixed. Here is a workaround

function serializeJSONIncludingDisabledFields (form) {
  var fields = form.find('[disabled]');
  fields.prop('disabled', false);
  var json = form.serializeJSON();
  fields.prop('disabled', true);
  return json;
}

Link to the issue

-1
votes
$('#field').removeAttr('disabled');
var formData = $(this).serializeArray();
$('#field').attr('disabled', 'disabled');

The solution above is better - alternatively you can just remove the disabled attribute from the element, serialize the fields then re-add the attribute.