compare elements and show alert or execute function in javascript

1

I'm practicing javascript and creating a task list manager.

I have my input field, which by pressing the button or giving enter passes the value of the input to a list of tasks below. What I want and I do not know how to do, is: when giving enter or click on the button compare what is in the value of the input with the elements that are already in the list and if there is already an element with the same text string send me an alert.

Thank you very much:)

        //variables
        var lista = document.getElementById("lista"),
        tareaInput = document.getElementById("tareaInput"),
        btnNuevaTarea = document.getElementById("btn-agregar");

        //funciones
        var agregarTarea = function(){
            var tarea = tareaInput.value,
                nuevaTarea = document.createElement("li"),
                enlace = document.createElement("a"),
                contenido = document.createTextNode(tarea);

        if (tarea === "") {
            tareaInput.setAttribute("placeholder", "agrega una tarea valida");
            tareaInput.className = "error";
            document.getElementById("contenedor_principal").classList.add("bg_red");
            return false;
        }

        //funcion revisar repetidos
      
     
        //agregamos el contenido a los enlaces
        enlace.appendChild(contenido);
        //le establecemos un atributo  href
        enlace.setAttribute("href", "#");

        //agregar enlace a la nueva tarea que es un elemento LI
        //ponemos elemento a dentro de li
        nuevaTarea.appendChild(enlace);
        //agregamos nueva tarea a la lista
        lista.appendChild(nuevaTarea);

        //limpiar input al click al boton
        tareaInput.value = "";

    //ciclo eventos borrando elementos de la lista
    for (var i = 0; i <= lista.children.length -1 ; i++)
{
    lista.children[i].addEventListener("click", function() {
        this.parentNode.removeChild(this);
    });
}

        
    };

    var comprobarInput = function() {
 tareaInput.className= "";
 tareaInput.setAttribute("placeholder", "agrega tu tarea");
 document.getElementById("contenedor_principal").classList.remove("bg_red");
    };
   
    var eliminarTarea = function (){
this.parentNode.removeChild(this);
    
    };
  
        //eventos
        //agregar tarea
        
        //agregar nueva tarea al hacer click al botón, o al presionar la tecla enter
        btnNuevaTarea.addEventListener("click", agregarTarea);
        addEventListener('keypress', function (e) {
            var key = e.which || e.keyCode;
            if (key === 13) { // 13 is enter
                agregarTarea();
            }
        });

  
        //comprobar input
        tareaInput.addEventListener("click", comprobarInput);


        //ciclo eventos borrando elementos de la lista
        for (var i = 0; i <= lista.children.length -1 ; i++)
        {
            //recorrer la lista desde el cero
            lista.children [i].addEventListener("click", eliminarTarea);
        }



     
* {
	margin: 0;
	padding: 0;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
}
 
body {
	background: #FAFAFA;
	font-family: arial, helvetica, sans-serif;
	font-size: 16px;
}
 
.wrap {
	margin: auto;
	max-width: 800px;
	width: 90%;
}
 
.principal {
	background: #198CFF;
	border-top: 20px solid #1066BB;
	color: #fff;
	padding: 50px 0;
	width: 100%;
}
 
.principal .formulario {
	color: #212121;
	text-align: center;
}
 
.principal .formulario input[type=text] {
	margin-bottom: 20px;
	padding: 10px;
	width: 100%;
}
 
.principal .formulario input[type=text].error {
	color: #F86969!important;
	-webkit-transition: all .3s ease-out;
	-moz-transition:  all .3s ease-out;
	-o-transition:  all .3s ease-out;
	transition:  all .3s ease-out;
}
 
.principal .formulario .boton {
	background: none;
	border: 1px solid #Fff;
	color: #fff;
	display: inline-block;
	font-size: 16px;
	padding: 15px;
}
 
.principal .formulario .boton:hover {
	border: 1px solid #fff;
}
 
/* - Tareas - */
.tareas .lista {
	list-style: none;
}
 
.tareas .lista li {
	border-bottom: 1px solid #B6B6B6;
}
 
.tareas .lista li a {
	color: #212121;
	display: block;
	padding: 20px 0;
	text-decoration: none;
}
 
.tareas .lista li a:hover {
	text-decoration: line-through;
}

.bg_red {
	background:#F86969;
	border-top: 20px solid #F86969;
	-webkit-transition: all .3s ease-out;
	-moz-transition:  all .3s ease-out;
	-o-transition:  all .3s ease-out;
	transition:  all .3s ease-out;

}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<link rel="stylesheet" href="css/estilos.css">
	<link rel="stylesheet" href="https://necolas.github.io/normalize.css/3.0.2/normalize.css">
	<title>Lista de Tareas</title>
</head>
<body>
	<div class="principal" id="contenedor_principal">
		<div class="wrap">
			<form class="formulario" action="">
				<input type="text" id="tareaInput"  placeholder="Agrega tu tarea" autofocus>
				<input type="button" class="boton" id="btn-agregar" value="Agregar Tarea">
			</form>
		</div>
	</div>

	<div class="tareas">
		<div class="wrap">
			<ul class="lista" id="lista">
	
			</ul>
		</div>
    </div>
    


</body>
</html>
    
asked by Francisco Kataldo 19.11.2018 в 22:01
source

1 answer

1

You can create an array with the contents of your list and then check if the element already exists in the array before adding it. Something like this:

//variables
        var lista = document.getElementById("lista"),
        tareaInput = document.getElementById("tareaInput"),
        btnNuevaTarea = document.getElementById("btn-agregar");
        var alista = [];

        //funciones
        var agregarTarea = function(){
            var tarea = tareaInput.value,
                nuevaTarea = document.createElement("li"),
                enlace = document.createElement("a"),
                contenido = document.createTextNode(tarea);

        if (tarea === "") {
            tareaInput.setAttribute("placeholder", "agrega una tarea valida");
            tareaInput.className = "error";
            document.getElementById("contenedor_principal").classList.add("bg_red");
            return false;
        }

        //funcion revisar repetidos        
        if (alista.indexOf(tarea) == -1) {
           alista.push(tarea);
        //agregamos el contenido a los enlaces
            enlace.appendChild(contenido);
            //le establecemos un atributo  href
            enlace.setAttribute("href", "#");

            //agregar enlace a la nueva tarea que es un elemento LI
            //ponemos elemento a dentro de li
            nuevaTarea.appendChild(enlace);
            //agregamos nueva tarea a la lista
            lista.appendChild(nuevaTarea);

            //limpiar input al click al boton
            tareaInput.value = "";

          //ciclo eventos borrando elementos de la lista
          for (var i = 0; i <= lista.children.length -1 ; i++)
          {
              lista.children[i].addEventListener("click", function() {
                  this.parentNode.removeChild(this);
              });
          }
        } else {
          alert("El elemento ya existe");
        }

        
    };

    var comprobarInput = function() {
 tareaInput.className= "";
 tareaInput.setAttribute("placeholder", "agrega tu tarea");
 document.getElementById("contenedor_principal").classList.remove("bg_red");
    };
   
    var eliminarTarea = function (){
this.parentNode.removeChild(this);
    
    };
  
        //eventos
        //agregar tarea
        
        //agregar nueva tarea al hacer click al botón, o al presionar la tecla enter
        btnNuevaTarea.addEventListener("click", agregarTarea);
        addEventListener('keypress', function (e) {
            var key = e.which || e.keyCode;
            if (key === 13) { // 13 is enter
                agregarTarea();
            }
        });

  
        //comprobar input
        tareaInput.addEventListener("click", comprobarInput);


        //ciclo eventos borrando elementos de la lista
        for (var i = 0; i <= lista.children.length -1 ; i++)
        {
            //recorrer la lista desde el cero
            lista.children [i].addEventListener("click", eliminarTarea);
        }
* {
	margin: 0;
	padding: 0;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
}
 
body {
	background: #FAFAFA;
	font-family: arial, helvetica, sans-serif;
	font-size: 16px;
}
 
.wrap {
	margin: auto;
	max-width: 800px;
	width: 90%;
}
 
.principal {
	background: #198CFF;
	border-top: 20px solid #1066BB;
	color: #fff;
	padding: 50px 0;
	width: 100%;
}
 
.principal .formulario {
	color: #212121;
	text-align: center;
}
 
.principal .formulario input[type=text] {
	margin-bottom: 20px;
	padding: 10px;
	width: 100%;
}
 
.principal .formulario input[type=text].error {
	color: #F86969!important;
	-webkit-transition: all .3s ease-out;
	-moz-transition:  all .3s ease-out;
	-o-transition:  all .3s ease-out;
	transition:  all .3s ease-out;
}
 
.principal .formulario .boton {
	background: none;
	border: 1px solid #Fff;
	color: #fff;
	display: inline-block;
	font-size: 16px;
	padding: 15px;
}
 
.principal .formulario .boton:hover {
	border: 1px solid #fff;
}
 
/* - Tareas - */
.tareas .lista {
	list-style: none;
}
 
.tareas .lista li {
	border-bottom: 1px solid #B6B6B6;
}
 
.tareas .lista li a {
	color: #212121;
	display: block;
	padding: 20px 0;
	text-decoration: none;
}
 
.tareas .lista li a:hover {
	text-decoration: line-through;
}

.bg_red {
	background:#F86969;
	border-top: 20px solid #F86969;
	-webkit-transition: all .3s ease-out;
	-moz-transition:  all .3s ease-out;
	-o-transition:  all .3s ease-out;
	transition:  all .3s ease-out;

}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<link rel="stylesheet" href="css/estilos.css">
	<link rel="stylesheet" href="https://necolas.github.io/normalize.css/3.0.2/normalize.css">
	<title>Lista de Tareas</title>
</head>
<body>
	<div class="principal" id="contenedor_principal">
		<div class="wrap">
			<form class="formulario" action="">
				<input type="text" id="tareaInput"  placeholder="Agrega tu tarea" autofocus>
				<input type="button" class="boton" id="btn-agregar" value="Agregar Tarea">
			</form>
		</div>
	</div>

	<div class="tareas">
		<div class="wrap">
			<ul class="lista" id="lista">
	
			</ul>
		</div>
    </div>
    


</body>
</html>
    
answered by 19.11.2018 в 22:08