1
I have a select where I can select more than one option(Multiple):
<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 into 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 way, the behavior is as follows:
When selecting the first element of select
it is added to li normally. But when we select the second option, in addition to adding the last one, it also adds the previous one to this one.
So I always wanted to get last option and add logo in li, instead of checking all of them to add.
Could someone help?