Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
(JS) Remove an option from select box JUST ONCE after calling function

I have this code where I want to add text to the select box when calling a function via clicking an input button.

I want the select box to have a default text when the page is loaded and no value is added to the array. And I want this text to vanish but I could still add many values from the input box and make them show on the select box.

So I made the input and select box with the following:

let num = document.querySelector('input#numtxt')
let lista = document.querySelector('select#seltxt')
let res = document.querySelector('div#res')
let valores = []

function adicionar() {
  if (isNumero(num.value) && !inLista(num.value, valores)) {
    lista.options[0] = null //
    valores.push(Number(num.value))
    let item = document.createElement('option')
    item.text = `Valor ${num.value} adicionado.`
    lista.appendChild(item)
  } else {
    window.alert('Valor inválido ou já existe!')
  }
}
<div>
  <p>TYpe a number between 1 and 100: <input type="number" name="num1" id="numtxt">
    <input type="button" value="Adicionar" onclick="adicionar()"></p>
</div>

<div>
  <p>
    <select name="sel1" id="seltxt" size="10">
      <option>Type a number above!</option>
    </select>
  </p>
  <p><input type="button" value="End" onclick="finalizar()"></p>
</div>

I've tried a lot of commands with boxvar.options[0] = null and boxvar.remove(0)but they all kept removing the first value which I need for the program.

Any sugestions?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

let num = document.querySelector('input#numtxt')
let lista = document.querySelector('select#seltxt')
let res = document.querySelector('div#res')
let valores = []
function adicionar() {
    if (isNumero(num.value) && !inLista(num.value, valores)) {
        if(!valores.length) {
            // If there are no values on list, delete whatever is inside of select
            lista.innerHTML = ''
        }
        valores.push(Number(num.value))
        let item = document.createElement('option')
        item.text = `Valor ${num.value} adicionado.`
        lista.appendChild(item)
    } else {
        window.alert('Valor inválido ou já existe!')
    }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

This is slightly verbose for clarity - if we add a data attribute we can filter on that and remove it if it exists. We can also filter by values and not add if the new one exists (it could be a data attribute if you do not want to set the value.

let lista = document.querySelector('#seltxt');
let res = document.querySelector('#res');
let valores = [];

function adicionar() {
  let num = document.querySelector('#numtxt');
  let opts = [...lista.options].filter((element, index) => {
    return element.dataset.default == "default";
  });
  console.log(opts);
  if (opts.length) {
    opts[0].remove();
  }
  let newValue = Number(num.value);
  // now if it already exists, don't add it
  let matchOpt = [...lista.options].filter((element, index) => {
    return element.value == newValue;
  });
  // we already have it so jump back out
  if (matchOpt.length) {
    return;
  }
  valores.push(newValue);
  let item = document.createElement('option');
  item.text = `Valor ${num.value} adicionado.`;
  item.value = newValue;
  lista.appendChild(item);
}
<div>
  <p>Type a number between 1 and 100: <input type="number" name="num1" id="numtxt">
    <input type="button" value="Adicionar" onclick="adicionar()"></p>
</div>

<div>
  <p>
    <select name="sel1" id="seltxt" size="10">
      <option data-default="default">Type a number above!</option>
    </select>
  </p>
  <p><input type="button" value="End" onclick="finalizar()"></p>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda