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.
JavaScript
x
11
11
1
function getFormData(formid){
2
var form = document.getElementById(formid);
3
let formdata = {};
4
Array.from(form.querySelectorAll('input, select, textarea'))
5
.filter(element => element.name)
6
.forEach(element => {
7
formdata[element.name] = element.type === 'checkbox' ? element.checked : element === 'select' ? element.map(option.selected => option.value) : element.value;
8
});
9
return formdata;
10
}
11
I would be grateful for help.
Advertisement
Answer
This works:
JavaScript
1
23
23
1
function getFormData(formid){
2
var form = document.getElementById(formid);
3
let formdata = {};
4
Array.from(form.querySelectorAll('input, select, textarea'))
5
.filter(element => element.name)
6
.forEach(element => {
7
if(element.type === 'checkbox'){
8
formdata[element.name] = element.checked;
9
} else if(element.options) {
10
var selected = [element.selectedOptions].map(option => option.value);
11
//var selected = [...element.options].filter(option => option.selected).map(option => option.value);
12
if (selected.length>1){
13
formdata[element.name] = selected;
14
} else {
15
formdata[element.name] = element.value;
16
}
17
} else {
18
formdata[element.name] = element.value;
19
}
20
});
21
return formdata;
22
}
23