最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to serialize multiple checkbox values by jQuery? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Nov 28, 2011 at 12:01 GooglebotGooglebot 15.7k45 gold badges144 silver badges247 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 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));

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

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

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.

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.

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

评论列表(0)

  1. 暂无评论