It is possible yes, even more using Jquery, there are several ways, if I am not mistaken Oce can bind an event for example: "onClick" in the options and then when the user clicks you perform a function that adds or removes this value in the array, in case the value of the option you passing the option as argument could take so: $(option).val();
to pass the option as argument you can do so
<option value="1" onClick="adicionarNoArray(this)">Option1</option>
I’m sorry about "If I’m not mistaken", I haven’t touched jQuery in a while, but I’m going to test it and then post a comment here saying whether it worked or not.
EDIT
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<select id="select" multiple>
<option value="1" onClick="adicionarArray(this)">Option1</option>
<option value="2" onClick="adicionarArray(this)">Option1</option>
<option value="3" onClick="adicionarArray(this)">Option1</option>
</select>
<script>
var valores = [];
function adicionarArray(option)
{
var index = valores.indexOf($(option).val());
if(index != -1)
{
valores.splice(index, 1);
}
else
{
valores.push($(option).val());
}
console.log(valores);
}
</script>
<body>
</html>
That should solve your problem. Maybe this is not the best way to do it and another can come with a better answer, but this way you can put the values as they are selected in an array and work with the values.
Excuse me, but
$("#opcoes").val()
no longer returns the list of selected values? What do you mean about "saving to a variable and keeping the chosen options"?– Woss
Possible! Try to get the value in the change event. As the field is multiple, an array will be returned.
– Maurivan