Skip to content
Advertisement

Merge multiple serializeobject to one?

is it possible to merge multiple serializeobject to one serializeobject? I will be using it in a post. The serializeobjects are created via for loop.

var data = [];
for (var i = 0; i < riid_count; i++) {
  data[i] = $('input[type=checkbox][data-record='+i+']').serializeObject();
  data[i].id = $('input[name=id][data-record='+i+']').val();
  console.log(data[i]);
}

$.ajax({
  url : '<?php echo base_url() . 'index.php/unsubscribe/submit' ?>',
  data: data (hopefully access the merged objects),
  method: "POST",
  processData: true,
  dataType: 'json',
  error: function(xhr, status, thrown)
  {
  // i have stuff here
  },
  success: function(data)
  {
  // i have stuff here
  }
});

And here is an example of how the <form> element could look:

<form>
  <input type="checkbox" data-record="0" class="selection" name="somename"> 
</form>

Depending on the data I get from the database there can be up to 10 (or even more) checkboxes.

Advertisement

Answer

I still have no idea what your HTML might look like and what optimizations we could still carry out. But the following collects the input fields of those elements following a “checked” checkbox. Maybe it is of some help to you?

function collectData(){
  var data = [];
  for (var i = 0; i < 7; i++) {
    data[i] = $('input[type=checkbox][data-record='+i+']').serializeArray();
    if (data[i][0]) data[i][0].id = $('input[name=id][data-record='+i+']').val();
  // console.log(data[i]);
  }
  let da=data.filter(e=>e.length).map(e=>e[0]);
  console.log(da)
}
$('button').click(collectData);
input[type=text] {width:25px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="checkbox" data-record="0" name="zero" value="zero">
<input type="text" data-record="0" name="id" value="000">
<input type="checkbox" data-record="1" name="one" value="un">
<input type="text" data-record="1" name="id" value="111">
<input type="checkbox" data-record="2" name="two" value="dos" checked>
<input type="text" data-record="2" name="id" value="222">
<input type="checkbox" data-record="3" name="three" value="tres">
<input type="text" data-record="3" name="id" value="333">
<input type="checkbox" data-record="4" name="four" value="cuatro" checked>
<input type="text" data-record="4" name="id" value="444">
<input type="checkbox" data-record="5" name="five" value="cinquo">
<input type="text" data-record="5" name="id" value="555">
<input type="checkbox" data-record="6" name="six" value="seis">
<input type="text" data-record="6" name="id" value="666">
</form>
<button> send </button>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement