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

152
Vistas
is there a correct way to add dynamically "forms" in a div-container with just JavaScript?

Im trying to create a dynamic form just with html, css, and JavaScript (or a little bit of JQuery) so my ploblem is I have this:

<div class="form-item">
                   <label for="form-container">Random Title:</label>
                   <div id="form-container">
                       ***Here is where I add dynamic "forms"***
                   </div>
                   <div>
                       <button type="button" class="add-form" onclick="AddForm()">Add form</button>
                   </div>
</div>

and the JavaScript is (I dont know if is the best solution but at least it works haha):

function addForm(){

    let container= document.getElementById('form-container');

    if (cnt<5){
        cnt+=1;
        container.innerHTML += `***the form but write on HTML format***`;
    } else {
        alert("¡you cant add anymore!");
    }

}

and I need something similar but to remove the forms that I added with the dynamic add button.

(form is between "" because it isnt actually a form it is just a div with inputs inside, because it is part of a bigger form with other inputs on other divs)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It is generally not a good idea to use inline event handlers (<button onclick=...).

Here's a a minimal reproducable example where delegated handling handles creation, submittal and deletion of maximally 5 dynamic forms within div#form-container.

Playground for this code.

const maxForms = 5;
document.addEventListener(`click`, handle);

function createFormHTML(n) {
  if (n > maxForms) {
    return alert(`No more forms allowed`);
  }
  return `
    <div data-dynamicform="${n}">
      <input type="text" placeholder="type something!">
      <button class="submit">Submbit</button>
      <button class="erase">Delete form</button>
    </div>`;
}

function handle(evt) {
  console.clear();
  
  if (evt.target.classList.contains(`add-form`)) {
    const container = document.querySelector(`#form-container`);
    container.dataset.nforms = +container.dataset.nforms + 1;
    const newForm = createFormHTML(+container.dataset.nforms);
    return newForm && container
      .insertAdjacentHTML(`beforeend`, newForm) || true;
  }
  
  if( evt.target.classList.contains(`submit`)) {
    return console.log(`submitted form #${
      evt.target.closest(`[data-dynamicform]`).dataset.dynamicform}`);
  }
  
  if (evt.target.classList.contains(`erase`)) {
    evt.target.closest(`[data-dynamicform]`).remove();
    const dynamicForms = document.querySelectorAll(`[data-dynamicform]`);
    dynamicForms.length && dynamicForms
      .forEach( (form, i) => form.dataset.dynamicform = i + 1 );
    document.querySelector(`#form-container`).dataset.nforms = 
      dynamicForms.length;
  }
}
body {
  margin: 1rem;
  font: normal 12px/15px verdana,arial;
}

#form-container {
  padding: 4px;
}

#form-container [data-dynamicform] {
  margin-bottom: 4px;
}
<div class="form-item">
  <div>
    <button type="button" class="add-form">Add form</button>
  </div>
  <div id="form-container" data-nforms="0">
    <h4>Your forms</h4>
  </div>
</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