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

118
Visualizações
Adding elements to form dynamically with javascript

I'm trying to add elements when a button is clicked, my code looks like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
    <form action="" method="POST" id="form-one">
        <button onclick="addChargingSchedule()">Add</button>
        <div class="cs"></div>
    </form>
</center>

<script>
    var elem = document.getElementsByClassName("cs");

    function addChargingSchedule() {
        var form = document.getElementById("form-one")
        var id = document.createElement("input");
        
        id.setAttribute("type", "text");
        id.setAttribute("name", "one");
        id.setAttribute("id", "one");
        id.setAttribute("placeholder", "1");
        
        form.appendChild(id)
    }
    </script>
</body>
</html>

The code works, when I click on the button, an input text is created but after like 0.1 secondes, the page is refreshed and the input disapears again. Someone knows what am I doing wrong?

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

0

You can add submit event listener and stop it like this:

form.addEventListener('submit', (event) => {
   event.preventDefault();
});

Working example taken by your code:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
    <form action="" method="POST" id="form-one">
        <button onclick="addChargingSchedule()">Add</button>
        <div class="cs"></div>
    </form>
</center>

<script>
    var elem = document.getElementsByClassName("cs");
 var form = document.getElementById("form-one")
    function addChargingSchedule() {
       
        var id = document.createElement("input");
        
        id.setAttribute("type", "text");
        id.setAttribute("name", "one");
        id.setAttribute("id", "one");
        id.setAttribute("placeholder", "1");
        
        form.appendChild(id);
    }
    
    form.addEventListener('submit', (event) => {
       event.preventDefault();
    });
    </script>
</body>
</html>

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