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

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

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 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