How to get values of elements created in the DOM

1

Good morning to all ... My goal is to put in an array the data that goes putting two inputs of my form, with the exception that when pressing the button more, the information is saved in an array, and it is created another new element "box / div", two more inputs to fill with its two corresponding button. And if I give the minus button, delete the information from that record in the array.

The problem I have is the following: I have managed to create the two inputs plus the two "+" and "-" buttons and eliminate the inputs and buttons. I can not put information in the array, only the first box of inputs, the following boxes I can not put the information in the array. I leave my code for you to take a look and I hope someone helps me. Thanks!

HTML FILE:

//cargamos el documento, sin el contenido multimedia

document.addEventListener("DOMContentLoaded",main);
function main(){
	var formacion = new Array();

	
	//recogemos en un array los datos que haya en formacion
	function recogerFormacion(){
		var anno = document.getElementById("year").value;
		var curso = document.getElementById("curso").value;
		var lista = document.getElementById("listaFormacionFinal");
		formacion.push(anno+" "+curso);
		console.log(formacion);
		var datos = document.createElement("li");
		datos.innerHTML = anno+" "+curso;
		lista.appendChild(datos);
	}	

	//function para el botón "+"
	function anadirCaja(){
		var divPrimero = document.getElementById("primero");
		var divResto = document.createElement("DIV");
		divPrimero.append(divResto);
		divResto.setAttribute("class", "visible");
		divResto.setAttribute("id", "primero");
		divResto.setAttribute("name", "cajas");				
		var inputAnno = document.createElement("input");
		var inputCurso = document.createElement("input");
		var inputBotonMenos = document.createElement("input");
		var inputBotonMas = document.createElement("input");
		inputAnno.setAttribute("type","text");
		inputAnno.setAttribute("id","year");
		inputAnno.setAttribute("size","2");
		inputCurso.setAttribute("type","text");
		inputCurso.setAttribute("id","curso");
		inputCurso.setAttribute("size","50");
		inputBotonMenos.setAttribute("type","button");
		inputBotonMenos.setAttribute("id","menos");
		inputBotonMenos.setAttribute("value","-");
		inputBotonMas.setAttribute("type","button");
		inputBotonMas.setAttribute("id","mas");
		inputBotonMas.setAttribute("value","+");
		inputBotonMas.addEventListener("click", anadirCaja);
        inputBotonMenos.addEventListener("click",quitarCaja);
		divResto.append(inputAnno);
		divResto.append(inputCurso);
		divResto.append(inputBotonMenos);
		divResto.append(inputBotonMas);
		recogerFormacion();
	}
	//funcion para el boton "-"
	function quitarCaja(){
		var cajas = document.getElementsByName("cajas");
		var cajaEliminar = document.getElementById("segundo");
		var totalCajas = cajas.length;
		console.log(totalCajas);
		if(totalCajas == 1){
			alert("No se puede eliminar");
			
		} else {
			cajaEliminar.parentNode.removeChild(cajaEliminar);
		}
    }

    //Ocultamos el formulario y mostramos los datos recogidos
    function mostrarDatosFinales(){
		if(recogerFormacion()){
			var ocultarFormulario = document.getElementById("contenedor");
			ocultarFormulario.className="oculto";
			var mostrarDatos = document.getElementById("datosFinales");
			mostrarDatos.className="visibleFinal";
		}

	}

	//boton de reset: blanqueamos los campos
	function borrarDatos(){
		document.forms.prueba.nombre.value ="";
		document.forms.prueba.apellidos.value ="";
		document.forms.prueba.dni.value ="";
		document.forms.prueba.correo.value ="";
		document.forms.prueba.year.value ="";
		document.forms.prueba.curso.value ="";
		document.forms.prueba.textarea.value ="";
	}
	var boton = document.getElementById("boton");
	boton.addEventListener("click",mostrarDatosFinales);
	var botonr = document.getElementById("botonb");
	botonr.addEventListener("click",borrarDatos);
	var mas = document.getElementById("mas");
    mas.addEventListener("click",anadirCaja);
    var menos = document.getElementById("menos");
    menos.addEventListener("click",quitarCaja);
	
}
#contenedor{
	width: 75%;
	margin: 0 auto;
}
input{
	display: block;
	border-radius: 3px;
}
#boton{
	margin-top: 5px;
}
#contenedor > #formulario >p{
	font-size: 25px;
	font-family: Courier, "Lucida Console", monospace;
	font-weight: bold;
}
#primero > input {
	display: inline;
	border-radius: 3px;
	margin: 2px;

}
input#mas{
	margin-left: 15px;	
	border-radius: 7px;
}
input#menos{
	margin-left: 15px;	
	border-radius: 7px;
}
.oculto{
	display:none;
}
.visibleFinal p{
	display:inline;
	width: 75%;
	margin-left: 0px;
}
#primero > input {
	display: inline;
	border-radius: 3px;
	margin: 3px;

}
#primero > input#mas{
	margin-left: 18px;	
	border-radius: 7px;
}
#primero > input#menos{
	margin-left: 17px;	
	border-radius: 7px;
}
#datosFinales{
	width: 75%;
	margin: 0 auto;
}div > div {
	display: inline-block;
}
<!DOCTYPE html>
<html>
<head>
	<title>Práctica a Entregar</title>
	<meta charset="utf-8">
	<script type="text/javascript" src="1.js">
		
	</script>
	<link rel="stylesheet" type="text/css" href="practica1.css">
</head>
<body>
	<h1>Solicitud de empleo</h1>
	<div id="contenedor" class="visible">		
		
		<form name="prueba" action="#" id="formulario">
			<p>Formacion:</p>
			<div class="visible" id="primero" name="cajas">
				<label for="year"></label>
				<input type="text" id="year" size="2" name="year">
				<label for="curso"></label>
				<input type="text" id="curso" size="50"  name="curso">
				<input type="button" id="menos" value="-">
				<input type="button" id="mas" value="+">
			</div>
			<button type="button" id="boton" value="validar">validar</button> 
			<button type="button" id="botonb" value="borrar">Borrar</button>
		</form>
	</div>
	<div id="datosFinales" class="oculto">
		<p>Formacion:</p>
		<ul id="listaFormacionFinal"></ul>
	</div>
</body>
</html>
    
asked by Sonia 11.11.2017 в 17:25
source

2 answers

0

With this answer I intend to approach your problem from another point of view, trying to give a simpler solution to something that, according to your initial logic seemed to be complicated.

The essential point of this solution is in the form of adding / deleting the data. Instead of having two buttons dedicated to each action, we can handle the add / delete action by means of a checkbox, which, when it is marked, will indicate that that element must be added and when it is unmarked that element should be deleted.

Here the aggregate is done immediately, because I do not know the whole context of your program. However, this approach to resolving the problem could have an additional advantage if you prefer: instead of constantly adding and deleting you could, when you finish, go through all the checkboxes, adding only those that are marked (thus making you gain in performance and simplicity).

Another advantage of this code is that it creates elements with different ids, so you can treat them as unique elements at any time.

For a more robust code, it would be necessary to submit the array to a function that avoids duplicates, in the case that two values are introduced that are the same, and that the array is ordered in case that elements above are unmarked or then marked ... note that all this would be avoided by only building your array at the end, from a validation button that read all the checkboxes, recovering only the values of those that are marked.

Another advantage in this regard is the possibility of correcting any value that has been written in error and that you decide to change later ...

Maybe there are easier ways to do this. I'm not a big expert on JS, but I think this solution could help you find a more appropriate solution to your problem.

I hope it serves you.

Note: Due to lack of time, I have elaborated only the code to add / delete the elements. The other actions, if you decide on this approach, would be simplified and even, perhaps, unnecessary.

document.addEventListener("DOMContentLoaded",main);
function main(){
	var formacion = new Array();
	var mas = document.getElementById("mas");
	var chkAgregar = document.getElementById("chkAgregar");
	chkAgregar.addEventListener("change", anadirCajaNew, true);
	
	var unaVez = function(element) { 	
		element.addEventListener('click', function(event) {
			var idCount=formacion.length;
			idYear="year"+idCount;
			idCurso="curso"+idCount;
			var divPrimero = document.getElementById("primero");
			var divResto = document.createElement("div");
			divPrimero.append(divResto);
			divResto.setAttribute("class", "visible"+idCount);
			divResto.setAttribute("id", "id"+idCount);
			divResto.setAttribute("name", "cajas");				
			var inputAnno = document.createElement("input");
			var inputCurso = document.createElement("input");
			var chkBox = document.createElement("input");
			var lblBox = document.createElement("label");
	
			chkBox.setAttribute("type","checkbox");
			chkBox.setAttribute("chk",idYear);
			chkBox.setAttribute("id", "id"+idCount);
			lblBox.innerHTML="Marque para agregar";

			inputAnno.setAttribute("type","text");
			inputAnno.setAttribute("id",idYear);
			inputAnno.setAttribute("size","2");
			inputCurso.setAttribute("type","text");
			inputCurso.setAttribute("id",idCurso);
			inputCurso.setAttribute("size","50");
	        chkBox.addEventListener("click",unaVez(chkBox));
	        chkBox.addEventListener("change",anadirCajaNew);
	
			divResto.append(inputAnno);
			divResto.append(inputCurso);
			divResto.append(chkBox);
			divResto.append(lblBox);

		}, {once: true});	
	
	};

	unaVez(chkAgregar);

	function anadirCajaNew(e){
		thisParent=e.srcElement.parentNode;
		thisInputs=thisParent.getElementsByTagName('input');
		anno=thisInputs[0].value;
		curso=thisInputs[1].value;

		if (this.checked){

			formacion.push(anno+" "+curso);
			console.log(formacion);

		}else{

			strId=this.id;
			intIndex=strId.replace(/\D/g, "");
			formacion.splice(intIndex, 1);
			console.log(formacion);
		
		}
	}
}
	<h1>Solicitud de empleo</h1>
	<div id="contenedor" class="visible">		
		
		<form name="prueba" action="#" id="formulario">
			<p>Formacion:</p>
			<div class="visible" id="primero" name="cajas">
				<label for="year"></label>
				<input type="text" id="year1" size="2" name="year">
				<label for="curso"></label>
				<input type="text" id="curso1" size="50"  name="curso">
				<input id="chkAgregar" type="checkbox" name="chkMas" />
				<label for="chkMas">Marque para agregar</label>

			</div>
			<button type="button" id="boton" value="validar">validar</button> 
			<button type="button" id="botonb" value="borrar">Borrar</button>
		</form>
	</div>
	<div id="datosFinales" class="oculto">
		<p>Formacion:</p>
		<ul id="listaFormacionFinal"></ul>
	</div>
    
answered by 12.11.2017 / 18:33
source
0

Reviewing the HTML markup generated by your code, I found the following observations:

  • HTML elements with duplicate IDs are created, which is not correct according to W3C - The id attribute . In the image shown below, it is denoted that the IDs are repeated.
  • New boxes are added inside the node of the initial box. In the following image you can see that the two new boxes with id="primero" are contained within the initial box with id="primero" .
  • Therefore, and understanding the real objective of what you are trying to achieve, I propose the following:

  • Reduce and adapt the HTML markup to use only the attributes necessary to clone the div that contains the fields to be saved, without duplicating their IDs.
  • The div that contains the fields to be saved, will be assigned a class row , only for readability.
  • Use Node.cloneNode to clone the divs with class row , when the + button is clicked, so there is no need to worry about renaming the IDs of each item, which has been added programmatically.
  • Show the + button only when there is a div box with class row , inside the form.
  • Store all the data in the boxes div with class row , only once, when you click on the button Validar , so that there is no need to try to update the value of the array formacion in some necessary position, and so, always have the array formacion with the updated data.
  • I attach the modified code version, with the necessary explanation.

    document.addEventListener("DOMContentLoaded", main);
    
    function main() {
      var formacion = []; // Declarar el array formación utilizando [].
      
      /*
       Esta función sirve para hacer mostrar el botón más cuando sólo esté una caja div con la clase row, en el formulario. Recibe como parámetro un número entero, donde -1 significa que no existe el elemento condicionado para mostrar.
       */
      function resetButtons(index) {
        var rows = document.getElementsByClassName("row"); // Obtener las cajas div con la clase row.
        if (index === -1) {
          var buttons = document.querySelectorAll("div.row input[hidden]"); // Obtener los botones con el atributo hidden.
          buttons[rows.length - 2].removeAttribute("hidden"); // Remover el atributo hidden del penúltimo botón de la variable buttons que contiene el atributo hidden.
        }
      }
    
      /*
       Esta función sirve para establecer la funcionalidad de eliminar las cajas div con la clase row, para los botones [-].
       */
      function setRemoveAction() {
      
        // 2. La función eliminar(e) recibe como parámetro el contexto del elemento al que fue invocado, en este caso, el botón [-].
        function eliminar(e) {
          // Declarar e inicializar las variables.
          var elems = document.getElementsByClassName("row"),
            len = elems.length;
          if (len > 1) {
            var current = e.target.parentElement.nextSibling; // Contiene el nodo inmediatamente siguiente donde se encuentra el botón [-].
            if (current.className !== undefined) {
              resetButtons(current.className.indexOf("row"));
            }
            e.target.parentElement.remove(); // Eliminar la caja div con clase row, del contexto que pertenece al botón [-] que se hizo clic.
            setRemoveAction(); // Ejecutar esta función para establecer la funcionalidad de eliminar cajas.
            setAddAction(); // Ejecutar esta función para establecer la funcionalidad de añadir cajas.
          } else {
            alert("No se puede eliminar.");
          }
        }
        // 1. Declarar e inicializar las variables.
        var menos = document.getElementsByClassName("menos"), i, len = menos.length, button;
        for (i = 0; i < len; i++) {
          button = menos[i]; // Encontrar el botón [-].
          button.onclick = eliminar; // Asignar la función eliminar() en su evento click.
        }
      }
    
      /*
       Esta función sirve para establecer la funcionalidad de añadir las cajas div con la clase row, para los botones [+].
       */
      function setAddAction() {
        
        // 2. La función agregar(e) recibe como parámetro el contexto del elemento al que fue invocado, en este caso, el botón [+].
        function agregar(e) {
          // Declarar e inicializar las variables.
          var node = e.target.parentElement, newNode = node.cloneNode(true);
          e.target.parentElement.parentElement.insertBefore(newNode, node.parentElement.lastChild.previousSibling); // Insertar el nodo clonado antes del último nodo que contiene los botones Validar y Borrar.
          e.target.setAttribute("hidden", "hidden"); // Ocultar el botón [+].
          setRemoveAction(); // Ejecutar esta función para establecer la funcionalidad de eliminar cajas.
            setAddAction(); // Ejecutar esta función para establecer la funcionalidad de añadir cajas.
        }
        // Declarar e inicializar las variables.
        var mas = document.getElementsByClassName("mas"), i, len = mas.length, button;
        for (i = 0; i < len; i++) {
          button = mas[i]; // Encontrar el botón [+].
          button.onclick = agregar; // Asignar la función agregar(), en su evento click.
        }
      }
    
      /*
       Esta función sirve para iterar sobre las cajas div con clase row para almacenar en el array formacion, un objeto {year: year, curso:curso}, conteniendo los datos, correspondientemente.
       */
      function getData() {
        var rows = document.getElementsByClassName("row"), i, len = rows.length;
        formacion = []; // Reinicializar el array formacion para siempre tener los datos actualizados.
        for (i = 0; i < len; i++) {
          formacion.push({
            year: document.getElementsByName("year")[i].value, // Utilizar el índice i, para acceder al elemento correspondiente.
            curso: document.getElementsByName("curso")[i].value
          });
        }
        return formacion; // Retonar el array formacion con los datos recopilados.
      }
      
      var btnValidar = document.getElementById("btnValidar");
      btnValidar.onclick = function() {
        // Declarar e inicializar las variables necesarias.
        var i, data = getData(), len = data.length, obj, html = "", datosFinales = document.getElementById("datosFinales"), listaFormacionFinal = document.getElementById("listaFormacionFinal");
        for (i = 0; i < len; i++) {
          obj = data[i];
          html += "<li>Year: ";
          html += obj.year;
          html += " - Curso: ";
          html += obj.curso;
          html += "</li>";
        }
        datosFinales.removeAttribute("class"); // Remover la clase de datosFinales para que sea visible.
        listaFormacionFinal.innerHTML = html; // Imprimir el contenido de la variable html en la listaFormacionFinal.
      };
    
      // Al inicio se deben ejecutar estas funciones para asignar las funcionalidades correspondientes.
      setRemoveAction();
      setAddAction();
    }
    #contenedor {
      margin: 0 auto;
      width: 75%;
    }
    
    .row {
      border: solid 1px #ccc;
      margin: 2px;
    }
    
    input {
      border-radius: 3px;
    }
    
    #contenedor #formulario p {
      font-family: Courier, "Lucida Console", monospace;
      font-size: 25px;
      font-weight: bold;
    }
    
    .oculto {
      display: none;
    }
    
    #datosFinales {
      margin: 0 auto;
      width: 75%;
    }
    
    div div {
      display: inline-block;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8" />
      <title>Práctica a Entregar</title>
    </head>
    
    <body>
      <h1>Solicitud de empleo</h1>
      <div id="contenedor">
        <form name="prueba" action="#" id="formulario">
          <p>Formacion:</p>
          <div class="row">
            <label>
              Año
              <input type="text" size="2" name="year" />
            </label>
            <label>
              Curso
              <input type="text" size="50" name="curso" />
            </label>
            <input type="button" class="menos" value="-" />
            <input type="button" class="mas" value="+" />
          </div>
          <div>
            <button type="button" id="btnValidar" value="validar">Validar</button>
            <button type="reset" id="btnBorrar" value="borrar">Borrar</button>
          </div>
    
        </form>
      </div>
      <div id="datosFinales" class="oculto">
        <p>Formacion:</p>
        <ul id="listaFormacionFinal"></ul>
      </div>
    </body>
    
    </html>

    The final result of the HTML markup is:

    I show in JSON format, the data that would contain the formacion array:

    [
      {
        "year": "2000",
        "curso": "Curso 1."
      },
      {
        "year": "2001",
        "curso": "Curso 1."
      },
      {
        "year": "2002",
        "curso": "Curso 3."
      },
      {
        "year": "2003",
        "curso": "Curso 4."
      }
    ]
    

    I hope it can help you. :)

        
    answered by 13.11.2017 в 03:55