I have a select where I can select more than one (multiple) option:
<select class="produtos form-control input-lg" multiple="multiple"
onchange="adicionaALista();" id="selectDeProdutos">
<c:forEach var="p" items="${produtos}">
<option value="${p.id}">${p.nome}</option>
</c:forEach>
</select>
I'm trying to get all the elements to add them in a list (li) after.
I'm doing it right now:
function adicionaALista() {
var select = document.getElementById("selectDeProdutos");
var options = select.options;
var opt;
for (var i = 0, iLen = options.length; i < iLen; i++) {
opt = options[i];
if (opt.selected) {
produto = {
nome : opt.text,
id : opt.value
}
adicionaElementosHtml(produto);
}
}
}
function adicionaElementosHtml(produto) {
var ul = document.getElementById("listaDeCompras");
var li = document.createElement("li");
li.appendChild(document.createTextNode(produto.nome));
ul.appendChild(li);
}
But it turns out that in this way, the behavior is as follows:
When you select the first element of select
it is added to the li normally. But when we select the second option, in addition to adding the latter, it also adds the previous one to it.
So, I always wanted to get the last option and add it to the li, instead of checking all of them to add.
Could someone help?