Skip to content
Advertisement

How to get form data with multiple select, similar to jquery val?

I work on solution to append form data (input, select, textarea) to FormData. I have problem with multiple select. Select value should be like jquery .val() – array if more than one option is selected.

  function getFormData(formid){
  var form = document.getElementById(formid);
  let formdata = {};
  Array.from(form.querySelectorAll('input, select, textarea'))
 .filter(element => element.name)
 .forEach(element => {
  formdata[element.name] = element.type === 'checkbox' ? element.checked : element === 'select' ? element.map(option.selected => option.value) : element.value;
  }); 
  return formdata;
  }

I would be grateful for help.

Advertisement

Answer

This works:

function getFormData(formid){
var form = document.getElementById(formid);
 let formdata = {};
 Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.forEach(element => {
 if(element.type === 'checkbox'){
formdata[element.name] = element.checked;
} else if(element.options) {
 var selected = [...element.selectedOptions].map(option => option.value);
 //var selected = [...element.options].filter(option => option.selected).map(option => option.value);
 if (selected.length>1){
 formdata[element.name] = selected;
 } else {
formdata[element.name] = element.value; 
 }          
} else {
formdata[element.name] = element.value; 
}
}); 
return formdata;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement