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

136
Visualizações
Adding an option to an HTML drop-down list using Javascript does nothing

I have copied several examples from this and other sites about how to add options to an HTML drop down list, but yet nothing happens. Here is my script:

<!DOCTYPE html>
<html><head></head>
<body>
<form>
<select name="p1customer" id="p1customer" onclick="addPC()">
<option>Apple</option>
</select>
<button type="button" onclick="addPC()">Insert option</button>
</form>
<script>
function addPC(){
            let x = document.getElementById("p1customer");
            let option1 = document.createElement("pc1");
            option1.text = "myCustomer";
            x.add(option1);     
    }  
</script>   
</body> 
</html>

Whether I click on my drop-down or the button the option never gets added. I have placed alert functions after each line of code and have verified that the objects exist, but the x.add method does nothing. It doesn't add the option to my list.

What am I missing?

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

0

I merely had to assign a value to the option as seen below and everything works.

function addPC(){
  let x = document.getElementById("p1customer");
  let option1 = document.createElement("pc1");
  option1.text = "myCustomer";
  option1.value = "myC";
  x.add(option1);     
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You have two mistakes in your code:

  1. pc1 is not a tag name. so you cannot use it in the createElement function.
  2. For adding an option you should use x.appendChild instead of x.add.
function addPC() {
    let x = document.getElementById("p1customer");
    let option1 = document.createElement("option");
    option1.text = "myCustomer";
    x.appendChild(option1);
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