Return a list of values present in select

Asked

Viewed 32 times

0

I made an interface where the user type a number and it is soon assigned to a value of select. The idea is that the user type a number and cannot type it again, but for this, I need that in each function call, a list of values present in the select, and I’m not getting it.

The Javascript code I tried and so far has not worked:

function validarNumero() {
    let numeroInput = Number(document.getElementById('inNumero').value)
    let tabela =  document.getElementById('numerosAnotados')
    let numeros = Array.from(tabela)

    if (numeros.indexOf(numeroInput) == -1) { // -1 == Não tem
      numeros.push(numeroInput) // Criando um registro
      let item = document.createElement('option')
      item.text = numeroInput
      tabela.appendChild(item)
    }
}
<section>
    <div>
        <p>Digite um numero [1 - 100]: <input type="number" name="" id="inNumero">
        <input type="button" value="Adicionar" onclick="validarNumero()"></p>
    </div>
    <div>
        <p><select id="numerosAnotados" size="10"></select><br>
        <input type="button" value="excluir" onclick="excluir()">
    </p>
    </div>
</section>

1 answer

0

One way to solve your problem would be to create a global array that would record all the numbers that have already been entered in select and then just need to check whether the number is already in this array.

In this way:

const numerosInseridos = []; // Array de Números Inseridos
function validarNumero() {
    let numeroInput = Number(document.getElementById("inNumero").value);
    let tabela = document.getElementById("numerosAnotados");
    let numeros = Array.from(tabela);
    if (numerosInseridos.includes(numeroInput)  || parseInt(numeroInput) > 100 ||  parseInt(numeroInput) < 0) {// Verificando se o número já foi inserido
        return;
    }
    numeros.push(numeroInput); // Criando um registro
    numerosInseridos.push(numeroInput); // Registando um número já inserido
    let item = document.createElement("option");
    item.text = numeroInput;
    tabela.appendChild(item);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.