Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
(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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda