Html select multiple get all values at onchange event
In the example below, i'm builiding arrays of selected options and selected values :
<select id="my-array" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
const myArray = document.getElementById('my-array');
myArray.addEventListener('change', (e) => {
const options = e.target.options;
const selectedOptions = [];
const selectedValues = [];
for (let i = 0; i < options.length; i++) {
if (options[i].selected) {
selectedOptions.push(options[i]);
selectedValues.push(options[i].value);
}
}
console.log(selectedOptions);
console.log(selectedValues);
});
This example might help without jQuery:
function getSelectedOptions(sel) {
var opts = [],
opt;
var len = sel.options.length;
for (var i = 0; i < len; i++) {
opt = sel.options[i];
if (opt.selected) {
opts.push(opt);
alert(opt.value);
}
}
return opts;
}
<select name="myarray[]" id="myarray" class="select2-select req" style="width: 90%;" onChange="getSelectedOptions(this)" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You can use jquery to solve it:
get_values=function(){
var retval = [];
$("#myarray:selected").each(function(){
retval .push($(this).val());
});
return retval;
};