I put you in situation.
I have a form with id="miformulario"
in which there are 2 buttons ( btnEnviar
, to send the form and show in a box / div
certain elements of the form, and btnEliminar
, to eliminate the box / div
that we previously created by btnEnviar
.
<input type="submit" value="Enviar" id="enviar" name="btnEnviar"/>
<input type="button" value="Eliminar" id="eliminar" name="btnEliminar"/>
The error is as follows: Why if I press btnDelete, having previously clicked btnSend to create the div shows me ALL the times the alert message?
JS / DOM code for the btnDelete button:
//Función para eliminar la caja resumen de los datos del formulario. DOM
//Inicializamos la variable "div" a null.
function eliminarCajaResumen(){
//Si existe la caja o el div...
var div = document.getElementById('div');
if(div !== null){
while (div.hasChildNodes()){
div.removeChild(div.lastChild);
}
}else{
alert ("No existe la caja previamente creada.");
}
}
JS / DOM code for the btnSend button:
//Inicializamos la variable "div" a null.
var div = null;
//Función que crea una caja con los datos del resumen. Se debe crear usando DOM.
function crearCajaResumen(){
//Si no hay ningun div...
if(div == null){
//Creamos el elemento/objeto que deseamos, sea <p> o <div> o <form>, etc.
div = document.createElement("div");
//DIV tiene la propiedad style, la cual permite acceder a atributos CSS. Ejemplo: div.style.width = "280px"; ...
div.setAttribute("style", "width: 280px; height: 170px; background-color: #FE775A; position: absolute; top: 20px; left: 20px;");
//Guardamos en una variable el body, aunque no haría falta, por cada HTML solo existe un body, entonces: "document.body".
//var body = document.getElementsByTagName("body")[0];
//Guardamos en una variable el elemento/objeto que deseamos, <center>
var center = document.getElementsByTagName("center")[0];
//Insertamos el elemento "div" antes que el "center".
document.body.insertBefore(div, center);
}
//Borramos los elementos que tenga la capa (previamente).
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
//Creamos un nodo de texto que agregaremos al div.
var titulo = document.createTextNode("DATOS RESUMEN FORMULARIO:\n\n");
//Añade un nuevo nodo al final de la lista.
div.appendChild(titulo);
//Declaramos un array donde guardaremos los textos seleccionados.
var seleccionados = [];
//Declaramos un array donde guardamos todos los elementos de tipo name=prefe.
var preferencias = document.getElementsByName("prefe");
//Recorremos ese array de elementos name=prefe.
for(var i=0; preferencias[i]; ++i){
//Si está marcada la casilla...
if(preferencias[i].checked){
//Agregamos al array "seleccionados" el valor de "preferencias[i]".
seleccionados.push(preferencias[i].value); //push() --> añade elementos al final de un array en Javascript.
}
}
//Añadimos un salto de línea.
var saltolinea1 = document.createElement("br");
div.appendChild(saltolinea1);
//Recorremos el nuevo array "seleccionados".
seleccionados.forEach(function(valor, index, array) {
//Por cada "seleccionado", asignamos: salto de línea, la preferencia "p"; y ambas variables las añadimos al "div".
var salto = document.createElement("br")
var p = document.createTextNode(valor);
div.appendChild(salto);
div.appendChild(p);
});
//Añadimos saltos de línea.
var saltolinea2 = document.createElement("br");
div.appendChild(saltolinea2);
var saltolinea3 = document.createElement("br");
div.appendChild(saltolinea3);
//Contamos los elementos que se han seleccionado.
if(seleccionados.length==1)
var contar = document.createTextNode("Has seleccionado " + seleccionados.length + " elemento."); // +contar_seleccionados()+
else
var contar = document.createTextNode("Has seleccionado " + seleccionados.length + " elementos."); // +contar_seleccionados()+
//Creamos el elemento salto de línea (br). En HTML, <br/>.
var salto = document.createElement("br");
//Agregamos al "div" ambas variables.
div.appendChild(contar);
div.appendChild(salto);
}
Call the event:
miformulario.btnEliminar.addEventListener("click", function(){
return eliminarCajaResumen();
}, false);