2

I modified the simple example of jQuery.post as

  $("#searchForm").submit(function(event) {
    event.preventDefault(); 
    var $form = $( this ),
        term = $( "input[name^=tick]:checked" ).serialize(),
        url = $form.attr( 'action' );
    $.post( url, { ticks: term, id: '55' },
      function( data ) {
          $( "#result" ).empty().append( data );
      }
    );
  });

This works for single checkbox with val() but not for multiple checkboxes in

<input type="checkbox" name="tick" value="'.$value.'" />

since serialize() should generateticks: termto be used astermin$.post`.

How can I make the serialize() to generate appropriate data for $.post

NOTE: I do not want to serialize the entire form but only checked values of checkbox INPUT.

Googlebot
  • 15,159
  • 44
  • 133
  • 229

6 Answers6

5

Simple value collector :) HTML

<input type="checkbox" class="selector" value="{value}"/>

JS

 var checked='';
            $('.selector:checked').each(function(){
                checked=checked+','+$(this).val();
            });

PHP

 $ids=explode(',',substr($_GET['param_with_checked_values'],1));
4

You could use .serializeArray() Ref: http://api.jquery.com/serializeArray/

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
3

In html code change name="tick" in name="tick[]" and you can use simply $(this).serialize(); to post all checked values.

Beppe
  • 31
  • 3
2

You can still use .serializeArray and use it in .post() like this:

var postData = {};
var form = $('#formId').serializeArray();
for (var i = 0; i < form.length; i++) {
    if (form[i]['name'].endsWith('[]')) {
        var name = form[i]['name'];
        name = name.substring(0, name.length - 2);
        if (!(name in postData)) {
            postData[name] = [];
        }
        postData[name].push(form[i]['value']);
    } else {
        postData[form[i]['name']] = form[i]['value'];
    }
}

$.post('/endpoint', postData, function(response) {

}, 'json');

postData will contain all form elements except the disabled ones. All checkbox values will be passed as an array just like when doing a normal form submission.

Stanimir Stoyanov
  • 1,623
  • 18
  • 29
1
let $form = $(".js-my-form");
let $disabled = $form.find(':input:disabled').removeAttr('disabled');
let formData = {};
$.each($form.serializeArray(), function (index, fieldData) {
    if (fieldData.name.endsWith('[]')) {
        let name = fieldData.name.substring(0, fieldData.name.length - 2);
        if (!(name in formData)) {
            formData[name] = [];
        }
        formData[name].push(fieldData.value);
    } else {
        formData[fieldData.name] = fieldData.value;
    }
});
$disabled.attr('disabled', 'disabled');
console.log(formData);

Its a variation of Stanimir Stoyanov answer with possibility to serialize disabled fields.

mu4ddi3
  • 135
  • 10
0
term = $("#input[name^=tick]:checked").map(function () {
    return this.value;
}).get();
term.join();
mozgras
  • 3,215
  • 3
  • 21
  • 17