create 5 elements dynamically

1

Actually I can create the 5 elements dynamically and delete them, but my problem is to generate them I put an id that is div1, div2, div3, div4 and div5, when I create the 5 elements and for example I delete the div3 and I recreate one so I left div1, div2, div4, div4 and div5, I use a variable num ++ and when I use a num--, how could I do when I delete for example div2 and div3, when creating me? put back those id's for example div1, div4, div5, div2 and div3.

num = 0;

function crear(obj) {

  if (num < 5) {
    num++;
    fi = document.getElementById('primerCurso'); // 1
    contenedor = document.createElement('div'); // 2
    contenedor.id = 'div' + num;
    contenedor.classList = 'col-md-12 form-inline'; // 3
    contenedor.style = 'margin-bottom:10px;';
    fi.insertBefore(contenedor, obj); // 4


    h2 = document.createElement('H2');
    h2.classList = 'personalizado';
    textoh2 = document.createTextNode('Curso con certificación');
    h2.appendChild(textoh2);
    contenedor.appendChild(h2);

    inputArchivo = document.createElement('input'); // 5
    inputArchivo.type = 'file'; // 6
    inputArchivo.name = 'curso_C' + num; // 6
    inputArchivo.id = 'curso_C' + num;
    inputArchivo.classList = 'form-control';
    inputArchivo.setAttribute('onChange', 'return validarCursoC' + num + '()');
    contenedor.appendChild(inputArchivo); // 7

    parrafo = document.createElement('P');
    parrafo.id = 'imagenCursoC' + num;
    contenedor.appendChild(parrafo);

    contenedor2 = document.createElement('DIV');
    contenedor2.classList = 'col-md-6 form-inline';
    contenedor.appendChild(contenedor2);

    label = document.createElement('LABEL');
    textoLabel = document.createTextNode('Fecha de incio del curso');
    label.appendChild(textoLabel);
    contenedor2.appendChild(label);

    inputDateInicio = document.createElement('INPUT');
    inputDateInicio.type = 'date';
    inputDateInicio.name = 'inicio_curso' + num;
    inputDateInicio.min = '1900-01-01';
    inputDateInicio.max = '<?php $hoy = date('
    Y - m - j '); echo $hoy; ?>';
    inputDateInicio.classList = 'form-control';
    inputDateInicio.id = 'inicio_curso' + num;
    inputDateInicio.style = 'width:11em;';
    contenedor2.appendChild(inputDateInicio);

    contenedor3 = document.createElement('DIV');
    contenedor3.classList = 'col-md-6 form-inline';
    contenedor.appendChild(contenedor3);

    label2 = document.createElement('LABEL');
    textoLabel2 = document.createTextNode('Fecha de incio del curso');
    label2.appendChild(textoLabel2);
    contenedor3.appendChild(label2);

    inputDateFin = document.createElement('INPUT');
    inputDateFin.type = 'date';
    inputDateFin.name = 'termino_curso' + num;
    inputDateFin.min = '1900-01-01';
    inputDateFin.max = '<?php $hoy = date('
    Y - m - j '); echo $hoy; ?>';
    inputDateFin.classList = 'form-control';
    inputDateFin.id = 'termino_curso' + num;
    inputDateFin.style = 'width:11em;';
    contenedor3.appendChild(inputDateFin);

    contenedor4 = document.createElement('DIV');
    contenedor4.classList = 'col-md-12 form-inline';
    contenedor.appendChild(contenedor4);

    label3 = document.createElement('LABEL');
    textoLabel3 = document.createTextNode('Breve descripcion del curso:');
    label3.appendChild(textoLabel3);
    contenedor4.appendChild(label3);

    textArea = document.createElement('TEXTAREA');
    textArea.classList = 'form-control';
    textArea.name = 'comentario' + 1;
    textArea.id = 'comment1';
    textArea.maxlength = 300;
    textArea.rows = 5;
    contenedor4.appendChild(textArea);

    ele = document.createElement('input'); // 5
    ele.type = 'button'; // 6
    ele.value = 'Borrar'; // 8
    ele.name = 'div' + num; // 8
    ele.onclick = function() {
      borrar(this.name)
    } // 9
    contenedor.appendChild(ele); // 7
  } else {

    alert('Solo puedes agregar 5 cursos, si deseas agregar más, en la pagina de "Editar empleado" lo puedes hacer.');
  }
}

function borrar(obj) {
  num--;
  fi = document.getElementById('primerCurso'); // 1 
  fi.removeChild(document.getElementById(obj)); // 10
}

the HTML:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Crear input file</title>
<link rel="stylesheet" href="">
</head>

<body>
	

 
 
<form method="post" action="">
<fieldset id="primerCurso">
<input type="button" value="Crear" onclick="crear(this)">
</fieldset>


</form> 
</body>
</html>
    
asked by Vick Muñoz 24.09.2018 в 22:27
source

1 answer

2

Create a small code to guide you. The first step I made was create a function where the divs were dynamically created (createDiv ()), then there inside that function I call the function that validates the id that you can use, that function is called idDiv () . Within the idDiv () function, I simply color a for where I evaluate whether that id is in use or not, if NO is in use I return it, it is very simple, I also made a button where you can delete the div and test how they are created and taking the id that corresponds to you as you want, I hope you serve:

const crearDiv = () => {

  const numDivs = document.getElementsByClassName("item").length;
  
  if(numDivs < 5){
  
    const contenedor = document.getElementById("contenedor-divs");
    let id = idDiv();
    let nuevoDiv = '<div id="'+id+'" class="item">
                      Este es el DIV con el id <strong>'+id +'</strong> <input type="button" class="eliminar" onClick="eliminarDiv(this)" value="Eliminar este DIV">
                    </div>';
    
    contenedor.insertAdjacentHTML("beforeend", nuevoDiv);
    
  }else{
    alert('Solo puedes agregar 5 cursos, si deseas agregar más, en la pagina de "Editar empleado" lo puedes hacer.');
  }

}

const idDiv = () => {
  
  for(var i = 1; i <= 5; i++){
    if(document.getElementById("div"+i) === null){
      return "div"+i;
    }
  }

}

const eliminarDiv = (obj) => {
  const div = obj.parentElement;
  div.remove();
}
#contenedor-divs{
  border:1px solid red;
  margin-top:10px;
  width:100%;
}

#contenedor-divs .item{
  border:1px solid blue;
  height:50px;
  margin-bottom:5px;
  margin-top:5px;
}
<form method="post" action="">
  <fieldset id="primerCurso">
  <input type="button" value="Crear Nuevo Div" onclick="crearDiv()">
  <div id="contenedor-divs"></div>
</fieldset>
    
answered by 24.09.2018 / 23:43
source