How to serialize multiple checkbox values by jQuery?
Solution 1
You could use .serializeArray() Ref: http://api.jquery.com/serializeArray/
Solution 2
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));
Solution 3
In html code change name="tick"
in name="tick[]"
and you can use simply $(this).serialize();
to post all checked values.
Solution 4
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
-
Googlebot about 4 years
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 generate
ticks: termto be used as
termin
$.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.