So, the JavaScript for my project stopped working after including the materialize JavaScript code needed to make my nav bar turn into a hamburger on mobile devices. I've tried placing my file at the bottom of the html, before the navbar script, and after it. Each time is the same, the hamburger and materialize js works but my js file that I'm using for password validation does not.. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register Page</title>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Our own style sheet -->
<link rel="stylesheet" href="style.css">
<!-- For icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
</script>
</head>
<body>
<nav>
<div class="nav-wrapper">
Logo
<i class="material-icons">menu</i>
<ul class="right hide-on-med-and-down">
<li>Home</li>
<li>About</li>
<li>Register</li>
<li>Contact</li>
</ul>
</div>
</nav>
<ul class="sidenav" id="mobile-demo">
<li>Home</li>
<li>About</li>
<li>Register</li>
<li>Contact</li>
</ul>
<div class="contact-box">
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" type="text" class="validate">
<label for="icon_prefix">Full Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">email</i>
<input id="icon_prefix" type="email" class="validate">
<label for="icon_prefix">Email</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">password</i>
<input id="psw" type="password" name="psw" class="validate" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required>
<label for="icon_prefix">Password</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
</div>
</div>
ss3
<div id="message">
<h5>Password must contain the following:</h5>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
<script type="text/javascript" src="validation.js"></script>
</body>
</html>
And here's the validation.js file:
// Script for validating password. This code was authored by w3schools at the url: https://www.w3schools.com/howto/howto_js_password_validation.asp
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
Am I placing my JavaScript file in the wrong area? I've tried placing it in the body with the same results too. Any help with this would be greatly appreciated :)
Please put your JS file at the end in the <body> tag. like this,
<body>
...
...
<div id="message">
<h5>Password must contain the following:</h5>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
...
...
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
</script>
<!-- my own JavaScript file -->
<script type="text/javascript" src="validation.js"></script>
</body>
And also please use a listener in your file to know that the entire document is first loaded so that your code will get the DOM which it is looking for.
window.addEventListener('load', (event) => {
// Script for validating password. This code was authored by w3schools at the url: https://www.w3schools.com/howto/howto_js_password_validation.asp
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
...
...
});
You can also use DOMContentLoaded if you are not concerned about the stylesheet loading.
Related
I'm trying to develop a dynamic form, where, if the user click on the plus icon, it should create two new fields in the same line.
The code that I have right now, it only create one single field, I tried to duplicate the same code in the funtion, but it only create two fields in vertical position and not in the same line.
Thank you Kindly !
Javascript code
var survey_options = document.getElementById('columna');
var add_more_fields = document.getElementById('add_more_fields');
var remove_fields = document.getElementById('remove_fields');
function Añadir(){
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('class','form-control');
newField.setAttribute('placeholder','Another Field');
survey_options.appendChild(newField);
}
function Eliminar(){
var input_tags = survey_options.getElementsByTagName('input');
if(input_tags.length > 2) {
survey_options.removeChild(input_tags[(input_tags.length) - 1]);
}
}
Html Code
<!doctype html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Awsome Fonts-->
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Styling -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- My Title-->
<title>Hello, world!</title>
</head>
<body>
<form class="Form" id="formulario">
<h1>Factibilidad Técnica y Operativa</h1>
<h2>Análisis de Infraestructura</h2>
<!-- Campos en Columnas-->
<div class="container" id="contenedor">
<div class="row" id="campo">
<div class="col" id="columna">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
<div class="col" id="columna">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
</div>
</div>
<!-- Iconos de Agregar / Eliminar Campos-->
<div class="Controls">
<i class="fa fa-plus-square"></i>Añadir
<i class="fa fa-minus-square"></i>Eliminar
</div>
</form>
<!-- JS Script-->
<script src="script.js"></script>
</body>
</html>
Very first point id value must not repeat. It should be unique. For More Info
In html, inputs are embedded in div so you should follow the same in JS to get same result.
div.col-lg-6 makes tags inside them to set half of screen when screen size is large. It will helps to your design
As I said, I created div.col-lg-6.mb-2 in JS and embedded input in div to get final result. mb-2 gives margin-bottom
div is embedded in div#campo and final result is here
var survey_options = document.getElementById('campo');
var add_more_fields = document.getElementById('add_more_fields');
var remove_fields = document.getElementById('remove_fields');
function Añadir(){
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'col-lg-6 mb-2')
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('class','form-control');
newField.setAttribute('placeholder','Another Field');
survey_options.appendChild(newDiv)
newDiv.appendChild(newField);
}
function Eliminar(){
var input_tags = survey_options.getElementsByTagName('input');
if(input_tags.length > 2) {
survey_options.removeChild(input_tags[(input_tags.length) - 1]);
}
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Awsome Fonts-->
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
<form class="Form" id="formulario">
<h1>Factibilidad Técnica y Operativa</h1>
<h2>Análisis de Infraestructura</h2>
<!-- Campos en Columnas-->
<div class="container" id="contenedor">
<div class="row" id="campo">
<div class="col-lg-6 mb-2">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
<div class="col-lg-6 mb-2">
<input type="text" class="form-control" placeholder="Infraestructura">
</div>
</div>
</div>
<!-- Iconos de Agregar / Eliminar Campos-->
<div class="Controls">
<i class="fa fa-plus-square"></i>Añadir
<i class="fa fa-minus-square"></i>Eliminar
</div>
</form>
</body>
Update
<!-- In HTML -->
<i class="fa fa-plus-square"></i>Añadir
<!-- In Script -->
function createTwoInput(){
Añadir();
Añadir();
}
If any clarification needed, Mention in comment
when I click on the "Todo Ekleyin" button, I get a warning. However, I would like this alert to appear only once per press, not multiple times, and can be pressed again after the alert disappears. How can I achieve this and?
Thank you in advance for your answer, good work. (If there is a method other than the method you suggested, I would be glad if you can write its name.)
// Tüm Elementleri Seçme
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
eventListeners();
function eventListeners() { // Tüm Event Listenerlar
form.addEventListener("submit", addTodo);
}
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") { // Alarm Verme
showAlert("danger","Lütfen Bir Todo Giriniz");
}
else {
addTodoToUI(newTodo);
}
addTodoToUI(newTodo);
e.preventDefault();
}
function showAlert(type,message){
const alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.textContent = message;
firstCardBody.appendChild(alert);
//setTimeout
setTimeout(function(){
alert.remove();
}, 1000);
}
function addTodoToUI(newTodo) { // String Değerini List Item olarak Ekleyecek.
// List Item Oluşturma.
const listItem = document.createElement("li");
// Link Oluşturma
const link = document.createElement("a");
link.href = "#";
link.className = "delete-item";
link.innerHTML = "<i class = 'fa fa-remove'></i>";
listItem.className = "list-group-item d-flex justify-content-between";
// Text Node
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
// Todo List'e List Item'ı Ekleme
todoList.appendChild(listItem);
// Ekleme Sonrası Input'tan yazı Silme
todoInput.value = "";
}
// Todo Ekleme Bilgi Mesajı
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<title>Todo List</title>
</head>
<body>
<div class="container" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body">
<form id="todo-form" name="form">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="todo" id="todo"
placeholder="Bir Todo Girin" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<hr />
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body">
<hr />
<h5 class="card-title" id="tasks-title">Todolar</h5>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="filter" id="filter"
placeholder="Bir Todo Arayın" />
</div>
</div>
<hr />
<ul class="list-group">
<!-- <li class="list-group-item d-flex justify-content-between">
Todo 1
<a href = "#" class ="delete-item">
<i class = "fa fa-remove"></i>
</a>
</li>-->
</ul>
<hr />
<a id="clear-todos" class="btn btn-dark" href="#">Tüm Taskları Temizleyin</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script src="berkay.js"></script>
</body>
</html>
You can put an integer in your alert function and every using array increase a one more.
For example, if you want after 5 times don't show alert.
var a = 0;
var b = true;
if (newTodo === "" || b) { // Alarm Verme
showAlert("danger","Please Give me a Todo!");
a++;
if(a == 5 ){
b = false;
}
}
I know this is a basic questions, but I am working on making a dynamic form and was having a bit of trouble figuring out how to delete elements that share the same class. I have looked around on the web and other posts for a means to accomplish this, but still was unable to figure it out.
I am new to this so I apologize for the basic question. Below, I have pasted the relevant code and my attempt at this. Would anyone be able to assist me?
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName){
if (ingCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement('directionSet');'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName){
if (dirCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
<!-- Required program scripts -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Style Sheets-->
<link rel="stylesheet" href="/styles/navBarStyle.css">
<link rel="stylesheet" href="/styles/myRecipesStyle.css">
<link rel="stylesheet" href="/styles/createRecipeStyle.css">
<link rel="stylesheet" href="/styles/errorMessageStyle.css">
</head>
<body>
<!-- Background image -->
<img id="background" src="/images/foodBackground.jpg" alt="">
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<%- include('../_partial/_messages'); -%>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/>
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
<!-- Required scripts to run app -->
<script src="/controls/newRecipeControl.js"></script>
<script src="/controls/errorMessageControl.js"></script>
</html>
Thanks for any help.
In your code you are using getElementById but there is no id called directionSet its a class.
You can simply use parentElement and remove to remove the newly added dynamic inputs by calling an onClick function.
In the onClick function removeElement() - this refers to the elements we have clicked and it will remove from the form.
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName) {
if (ingCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement(this);'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName) {
if (dirCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' onClick='removeElement(this);' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
elementId.parentElement.remove()
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
</head>
<body>
<!-- Background image -->
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" />
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
</html>
I'm doing a simple to do app in vanilla JavaScript where I'm trying to reset the input field after every click but for some reason it is not re-setting after every click.
it does reset after you click on the input field, but what I want is for the input field to reset after the clicking the "add" button and not having to click on input field.
the input field is not inside a <form>
this is my function to try to reset the input field
document.getElementById("task").onclick = function() {
Reset();
}
function Reset() {
document.getElementById("task").value = null;
}
<div class="row">
<div class="col s12">
<div class="input-field inline">
<input id="task" type="text">
<label for="email" data-error="wrong" data-success="right">Add a todo</label>
</div>
<a id="add" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
</div>
this is the problem now for some reason its affecting the localstorage:
function getTodos(){
var todos = new Array();
var todos_str = localStorage.getItem('todo');
if(todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
// Please do not use inline event handlers, use this instead:
document.getElementById("add").onclick = function() {
Reset();
}
function Reset() {
document.getElementById("task").value = null;
}
function add(){
var task = document.getElementById('task').value;
var todos = getTodos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove() {
var id = this.getAttribute('id');
var todos = getTodos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = getTodos();
var html = '<ul>';
for(var i = 0; i < todos.length; i++) {
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '"> x </button></li>';
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for( var i = 0; i < buttons.length; i++){
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>to do app</title>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="navbar-fixed">
<nav>
<div class="nav-wrapper">
Logo
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>Sass</li>
<li>Components</li>
<li>JavaScript</li>
</ul>
</div>
</nav>
</div>
<div class="row">
<div class="col s12">
<div class="input-field inline">
<input class="reset-task" id="task" type="text">
<label for="email" data-error="wrong" data-success="right">Add a todo</label>
</div>
<a id="add" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
</div>
<div id="todos"></div>
<script src="app.js"></script>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</body>
</html>
Your example does work but you just used the wrong id.
Use the add id instead of the task id and everything should work fine.
document.getElementById("add").onclick = function() {
Reset();
}
function Reset() {
document.getElementById("task").value = null;
}
<div class="row">
<div class="col s12">
<div class="input-field inline">
<input id="task" type="text">
<label for="email" data-error="wrong" data-success="right">Add a todo</label>
</div>
<a id="add" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
</div>
Well, it's not clearly where you'd like to get the click event triggered, so I'm assuming that first option is on the body, so:
document.body.addEventListener("click", Rest);
Before your "document.getElementById("task").onclick" should help, there is just a little trick to get this working properly here:
Why is the onclick event on the body element not working?
It's the something if what you like is getting it triggered on element a click event:
document.getElementById("add").onclick = function()......
I added a breakpoint at login function. When I submit the form, the login function should be called; but it's not called. And when I log in, the page doesn't redirect to window.location. I want the page to be redirected if the login credentials are the same as the one in local storage. I know we shouldn't validate your code client side. But for now, let's just ignore that.
var db = window.localStorage;
function signUp() {
var signupFormDt = document.querySelector('#signup-form');
var email = signupFormDt.querySelector('input[name="email"]');
var password = signupFormDt.querySelector('input[name="password"]');
var userName = signupFormDt.querySelector('input[name="name"]');
db.setItem(userName.name, userName.value);
db.setItem(email.name, email.value);
db.setItem(password.name, password.value);
}
function login() {
var loginFormDt = document.querySelector('#login-form');
var logEmail = loginFormDt.querySelector('input[type="email"]');
var logPass = loginFormDt.querySelector('input[type="password"]');
if (db.email == logEmail.value && db.password == logPass.value) {
window.location = 'http://www.google.com';
} else {
window.location = "http://www.google.com";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!--Link to StyleSheet-->
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
</head>
<body>
<header>
<div class="container">
<h1>
</h1>
<nav>
<ul class="clearfix">
<li>
<a href="#">
<h4>Home</h4>
</a>
</li>
<li>
<a href="../html/about.html">
<h4>About</h4>
</a>
</li>
<li>
<a href="#">
<h4>Contact</h4>
</a>
</li>
<li>
<a href="#">
<h4 id="social">Social</h4>
<div class="arrow"></div>
<ul>
<li>Twitter</li>
<li>Facebook</li>
<li>Instagram</li>
<li>Snapchat</li>
<li>Tumblr</li>
</ul>
</a>
</li>
</ul>
<!-- end of ul of main nav-->
</nav>
<!--end of nav-->
</div>
<!--end of container-->
</header>
<main>
<section>
<h3>login Page</h3>
<div id="login">
<p>Myselfie Tech</p>
<form method="Post" id="login-form">
<p>
<input type="email" name="email" id="email" placeholder="email" required>
</p>
<p>
<input type="password" name="password" id="password" placeholder="password" required>
</p>
<p>
<button type="submit" onsubmit="login()">Submit Query</button>
</p>
<p>
<button onclick="window.location='../html/index.html'">Back</button>
</p>
</form>
</div>
</section>
</main>
<footer>
<p>
<center><small>©Copyright 2017 programmers inc.</small></center>
</p>
</footer>
<!--Link to Javascript-->
<script src="../javascript/scripts1.js"></script>
</body>
</html>
A button element does not have an onsubmit attribute. You should put that attribute on the form tag for it to work. Also make sure that the form submission is cancelled, since you want to control the navigation differently, with window.location:
Add return:
<form onsubmit="return login();">
Add return false, and .href after location:
function login() {
var loginFormDt = document.querySelector('#login-form');
var logEmail = loginFormDt.querySelector('input[type="email"]');
var logPass = loginFormDt.querySelector('input[type="password"]');
if (db.email == logEmail.value && db.password == logPass.value) {
window.location.href = 'http://www.google.com';
} else {
window.location.href = "http://www.google.com";
}
return false; // <------
}
Try using input tag instead of button for submit
something like
<input id="clickMe" type="button" value="Submit Query" onclick="login()" />