How to serialize with input disable?

4

In a response in the SOEN

They pass an approach of temporarily disabling the fields:

Example:

var myform = $('#myform');

 // Encontra os elementos e remove o atributo disable
var disabled = myform.find(':input:disabled').removeAttr('disabled');

 // serialize o form
var serialized = myform.serialize();

 // coloca todos os elementos que foram desabilidados disable
disabled.attr('disabled','disabled');

Is there a more efficient way to serialize() in form fields that are disabled?

    
asked by anonymous 20.11.2015 / 14:02

1 answer

1

You could solve this problem by traversing the disabled elements to get the name e o value and at the end concatenating with the serialized string to send to the server.

Example:

function getDisableInput(form) {
   var input = $("#" + form + " input:disabled");
   var result = '';
   $.each(input, function (key, val) {
      result += "&" + val.name + '=' + val.value;
   });
   return result;
}

var disableInput = getDisableInput('form');  
var dados = $("#form").serialize() + disableInput; // agora é só enviar para o servidor.

Another interesting way to achieve the same result is by traversing all fields of the 'input[type=text]' selector so you do not even have to use serialize for type text input's.

Example 2:

var dados = '';

$('input[type=text]').each(function() {
  dados += '&' + this.id + '=' + this.value;
});

console.log(dados);
    
20.11.2015 / 16:47