-1
The code below does not answer correctly, sometimes puts two commas, sometimes only removes the commas and sometimes works. ex when I click delete it looks like this in the input: [date1,date2 date3].
function grava(id) {
var vara = document.getElementById("id-select").value;
vara = vara.replace(',,', ',');
if (vara.length == 0) {
document.getElementById("inter").value = id.value + ",";
} else {
document.getElementById("inter").value = vara + id.value + ",";
}
var valor = id.value;
var markup = "<tr id='" +
valor.trim() +
"' >" +
"<td style='border: 1px solid rgb(228, 228, 228); cursor: pointer; color: #000; text-align: center;'>" +
valor.trim() +
" </td>" +
"<td style='border: 1px solid rgb(228, 228, 228); cursor: pointer; color: #000; text-align: center;'>" +
"<button type='button' id='delete-row' title='Excluir' onClick='deleteRow(this,\"" +
valor.trim() +
"\")' class='btn btn-danger delete'> <i class='fa fa-trash'></i></button>" +
"</td>" + "</tr>";
$("#tbOptions tbody").append(markup);
}
function deleteRow(btn, item) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
var vara = document.getElementById("inter").value;
vara = vara.replace(',,', ',');
var array = vara.split(',');
var operadores = "";
for (var i = 0; i < array.length; i++) {
var id = array[i].trim().replace(' ', '').toLowerCase();
var comp = item.trim().replace(' ', '').toLowerCase();
if (id != comp && id.length > 0) {
operadores += array[i].trim() + ",";
}
}
operadores = operadores.substring(0, operadores.length - 1);
document.getElementById("inter").value = operadores;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
<select id="id-select" onchange="grava(this)">
<option value="opcao1">opcao1</option>
<option value="opcao2">opcao2</option>
<option value="opcao3">opcao3</option>
<option value="opcao4">opcao4</option>
<option value="opcao5">opcao5</option>
</select>
</form>
<table class="table table-hover table-striped table-bordered" id="tbOptions">
<thead>
<tr style="background-color: rgb(228, 228, 228);">
<th style="cursor: pointer; color: #000; text-align: center;"> Opções Selecionadas</th>
<th style="cursor: pointer; color: #000; text-align: center;"> </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<input type="text" id="inter">
And I can insert the same option twice. What’s wrong with it?
Nice, thank you very much. How do I "check if the option has already been added" in my code?
– Lau de Souza
In my example I assign an id to tr, corresponding to the name of the selected option. After that I only check whether it exists or not.
– Henrique