dimanche 18 février 2018

How to send multiple checked values to db and append value to each object?

I have a form with checkboxes. One or many can be selected to be send to db.

The form is used to register damages on assets, so there is a relation to "current_id" which is the unique asset. 1:n relation. Since I need to send the current_id as a foreign key I push it on the form array like so formData.push({name: 'id', value: current_id});

This works fine when only one checkbox is selected. But when I have multiple options checked I cannot send to the server. I struggle to solve this. I have looked into using map, but I was not sure how to implement it to send a correct array to the database.

Help would be much appreciated

$('form').submit(function(e){
  e.preventDefault();
  let formData = $(this).serializeArray();
  
  formData.push({name: 'id', value: current_id});
});

$.post({
  type: 'POST',
  url: '/api',
  data: formData
})

// what i tried..
// for multple checked boxes
// this did not work

//formData.forEach(function (data){
//  data.push({name: 'id', value: current_id});
//  $.post({
//    type: 'POST',
//    url: '/api',
//    data: formData
//  })
//})
<form id="damages">
  <input type="checkbox" name="damage" value="loose" checked="checked" />
  <input type="checkbox" name="damage" value="broken" />
</form>



Aucun commentaire:

Enregistrer un commentaire