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.

6 Answers 6

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));
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

you can store the values in array and than serialise it.
3

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

1 Comment

Wow, this is quite the easiest way to get multible checkbox values!
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.

Comments

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.

Comments

0
term = $("#input[name^=tick]:checked").map(function () {
    return this.value;
}).get();
term.join();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.