How to retrieve checkbox value in form using serialize ()?

0

I have a form in which it is dynamically created using the append method. The result is something in this format:

$('#form').append("<tr><td class='td-min'><input value='"+item.role+"'"+
    +" name='"+item.prefix+"' type='checkbox'/> "+item.role+"</td></tr>'");

Above would be basically a form item, in which a list of items is generated dynamically.

Below, using AJAX, this is how I want to write to the database, but I do not know how to retrieve the values of checkbox . See:

jQuery('#form').submit(function(){
    var dados = jQuery(this).serialize();
    jQuery.ajax({
        type: "POST",
        url: "http://api.server.com/resgata",
        success: function( data )
        {

        }
    });
  return false;
});

How to retrieve values of the% dynamic% (both checked and unchecked ) on the form using the checkbox's method? Is it possible?

    
asked by anonymous 15.05.2017 / 04:38

2 answers

0

An alternative is to get the values of checkboxs and concatenate with the serialize method, since serialize() transforms form values into a valid querystring :

jQuery('#form').submit(function(){
    var dados = jQuery(this).serialize() + getUnchecks();
    jQuery.ajax({
        type: "POST",
        url: "http://api.server.com/resgata",
        success: function( data )
        {

        }
    });
  return false;
});

function getUnchecks() {
  var uncheckdItemsStr = '';
  var domElement = document.getElementById("form");
  jQuery(domElement).find("input:checkbox:not(:checked)").each(function() {
    uncheckdItemsStr += '&' + jQuery(this).prop('name') + '=' + jQuery(this).prop('value');
  });

  return uncheckdItemsStr;
}

The return of getUnchecks will be something like:

&abc=cba&qwe=ewq&qwe=ewq
    
15.05.2017 / 14:29
0

With jQuery you can basically do this:

// Conversão de formulário para objeto Array
var dados = $(this).serializeArray();

// Conversão de objeto para URL
var query = $.param(dados);

dados should be something like:

[
    { name: 'nameDeUmaCheckBox', value: 'valorDaCheckBox' },
    ...
]

If you want the value of each checkbox to serialize as its respective checked state, try:

var transform = $(this).clone();

// Muda o valor das checkboxes para o estado checked
// (0 ou 1 no exemplo)
transform.find('input[type=checkbox]').each(function() {
    this.value = this.checked ? 1 : 0;
});

Then:

var dados = $(transform).serializeArray();
var query = $.param(dados);
    
15.05.2017 / 15:41