What are the methods to limit the number and time of alerts? - javascript

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;
}
}

Related

How can I redirect to another page after verifying the credit card validation?

I need help about redirect another page after credit card valitaditon success.php
Well i dont know anything about vue.
i found something like (onSubmit () {
axios.get('success.php', { )
Something like this? Any help to this poor guy. Thanks :)
Here is vue codes.
<script src="../dist/vue-credit-card-validation.js"></script>
<script type="text/javascript">
const { createApp, ref } = Vue;
const Example = {
computed: {
cardBrandClass(){
return this.getBrandClass(this.cardBrand);
}
},
data() {
return {
cardNumber: null,
cardExpiry: null,
cardCvc: null,
cardPostal: null,
cardErrors: {},
// declaring card-brand in data{} enables card brand name/classes.
cardBrand: null,
}
},
methods: {
validate: function(){
// init
this.cardErrors = {};
// validate card number
if(!this.$cardFormat.validateCardNumber(this.cardNumber)){
this.cardErrors.cardNumber = "Invalid Credit Card Number.";
};
// validate card expiry
if (!this.$cardFormat.validateCardExpiry(this.cardExpiry)) {
this.cardErrors.cardExpiry = "Invalid Expiration Date.";
};
// validate card CVC
if (!this.$cardFormat.validateCardCVC(this.cardCvc)) {
this.cardErrors.cardCvc = "Invalid CVC.";
};
},
reset: function(){
this.cardErrors = {};
this.cardNumber = null;
this.cardExpiry = null;
this.cardCvc = null;
this.cardPostal = null;
this.$refs.cardNumInput.focus();
},
prefill: function(ccNum){
this.cardNumber = ccNum;
this.$cardFormat.setCardType({
currentTarget : this.$refs.cardNumInput,
value: ccNum
});
},
getBrandClass: function (brand) {
let icon = '';
brand = brand || 'unknown';
let cardBrandToClass = {
'visa': 'fab fa-cc-visa',
'mastercard': 'fab fa-cc-mastercard',
'amex': 'fab fa-cc-amex',
'discover': 'fab fa-cc-discover',
'diners': 'fab fa-cc-diners-club',
'jcb': 'fab fa-cc-jcb',
'unknown': 'fa fa-credit-card',
};
if (cardBrandToClass[brand]) {
icon = cardBrandToClass[brand];
};
return icon;
}
},
watch: {
// handle auto-focus to next field
// Note: since CVC can be 3 OR 4 digits we don't watch it
cardNumber: function(val){
if(this.$cardFormat.validateCardNumber(val)){
this.$refs.cardExpInput.focus();
}
},
cardExpiry: function (val) {
if (this.$cardFormat.validateCardExpiry(val)) {
this.$refs.cardCvcInput.focus();
}
}
},
onMounted(){
this.$refs.cardNumInput.focus();
}
};
const app = createApp(Example);
app.use(VueCreditCardValidation);
app.mount('#app');
</script>
Here is html
<!DOCTYPE html>
<html>
<head>
<title>Card validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!-- Libraries only required for demo. -->
<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://unpkg.com/vue#next"></script>
</head>
<body>
<form >
<div class="row pt-4">
<div class="col-sm-12 col-md-6 col-lg-4">
<div class="form-group">
<label>Card Number:</label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i :class="cardBrandClass"></i></span>
</div>
<input ref="cardNumInput" :data-error="(cardErrors.cardNumber)?true:false" v-model="cardNumber" type="tel" class="form-control" placeholder="#### #### #### ####" v-cardformat:formatCardNumber>
</div>
<div v-if="cardErrors.cardNumber" class="error">
<small>{{ cardErrors.cardNumber }}</small>
</div>
</div>
</div>
</div>
<div class="row pt-2">
<div class="col-4 col-lg-2">
<div class="form-group">
<label>Card Expiration:</label>
<input ref="cardExpInput" id="card-exp" :data-error="(cardErrors.cardExpiry)?true:false" v-model="cardExpiry" maxlength="10" class="form-control" v-cardformat:formatCardExpiry>
<div v-if="cardErrors.cardExpiry" class="error">
<small>{{ cardErrors.cardExpiry }}</small>
</div>
</div>
</div>
<div class="col-4 col-lg-2">
<div class="form-group">
<label>Card CVC:</label>
<input ref="cardCvcInput" :data-error="(cardErrors.cardCvc)?true:false" v-model="cardCvc" class="form-control" v-cardformat:formatCardCVC>
<div v-if="cardErrors.cardCvc" class="error">
<small>{{ cardErrors.cardCvc }}</small>
</div>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label>Restrict Numeric:</label>
<input placeholder="Only numbers can be entered here..." v-model="cardPostal" class="form-control" v-cardformat:restrictNumeric>
</div>
</div>
</div>
<div class="row">
<div class="col-12 pt-2">
<button type="button" class="btn btn-primary" #click="validate">Validate Card Details</button>
<button type="button" class="btn btn-light" #click="reset">Reset</button>
</div>
</div>
</form>
</body>
</html>
I need help after validation confirm send to success.php page. Thanks.
If you are working with php/html files instead of an single page app, you could simply redirect the user with some basic javascript.
In your method, when you need to redirect the user after validating the card succesfully, just type:
window.location.replace("http://my-url.com/my.page");

How do I handle multiple created buttons with JavaScript in a ToDo web script that all have the same class name?

I am making a simple ToDo app that when you write in the input form and submit it, it posts it neatly in a flex-box design below.
After it adds Your writing to the ToDo list at the bottom, JavaScript clears the input selection box.
My problem is that all the created ToDo list items are the SAME! They have the same class name and structure. I do not know how to handle all the buttons that are created so that when you click on the <button class='delete-btn'>x</button> it deletes only that button.
I have put all the writing templates created into a simple array called arrayOfText.
I was hoping I could delete the specific <div class='todo-div'>...</div> that the button was clicked from and then rewrite the whole .innerHTML of the ToDo list section.
This basically updates it and removes the div from the ToDo list that the button was clicked from, but I cannot seem to get it to work.
If you need more information, please message me.
"use strict";
const outputSection = document.querySelector("#output-section");
outputSection.innerHTML = "";
const writingArea = document.querySelector("#writing-area");
const publishBtn = document.querySelector(".default-btn");
const deleteBtns = document.getElementsByClassName("delete-btn");
const allToDoDivs = document.getElementsByClassName("todo-div");
const arrayOfText = [];
const cutAndPrintFunc = function (e) {
e.preventDefault();
//take writing in and print it to the current agenda
// clear the writing area
if (writingArea.value != "") {
const date = new Date();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDay()).padStart(2, "0");
const year = date.getFullYear();
const hour = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
const AMorPM = date.getHours() > 12 ? "PM" : "AM";
const minute = String(date.getMinutes()).padStart(2, "0");
const template = `
<div class="todo-div">
<h1 class="text-content">${writingArea.value}</h1>
<button class="delete-btn">x</button>
<p class="date-p">${month}/${day}/${year} --- requested # ${hour}:${minute} ${AMorPM} </p>
</div>`;
arrayOfText.push(template);
outputSection.insertAdjacentHTML("beforeend", template);
writingArea.value = "";
Array.from(allToDoDivs).forEach((el, ind) => {
if (ind % 2 === 0) {
el.style.backgroundColor = "#3ce815";
el.lastElementChild.style.color = "black";
}
//-----this does not work
// Array.from(allToDoDivs)[
// allToDoDivs.length - 1
// ].children[1].addEventListener("click", () => {
// console.log(this);
// // arrayOfText.pop(this);
// // outputSection.innerHTML = arrayOfText.join("");
// });
});
}
};
//publish text by hitting enter or pressing the plus sign in textbox
publishBtn.addEventListener("click", cutAndPrintFunc);
<!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" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Comfortaa&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="/style.css" type="text/css" />
<title>Griffin's ToDo List</title>
</head>
<body>
<header>
<h1>
Welcome to <em style="text-decoration: underline">Griffin's</em> To-Do
List
</h1>
<div id="mini-flex-div">
<div class="ball" id="blue"> </div>
<div class="ball" id="orange"> </div>
<div class="ball" id="purple"> </div>
<p>What needs to be done today...</p>
<div class="ball" id="purple"> </div>
<div class="ball" id="orange"> </div>
<div class="ball" id="blue"> </div>
</div>
</header>
<main>
<div id="writer-div">
<form>
<input
id="writing-area"
type="text"
rows="1"
placeholder="Lets get this out of the way..."
maxlength="50"
spellcheck="true"
autofocus
></input>
<button class='default-btn'>+</button>
</form>
</div>
</main>
<div id="bottom-header">
<h1 id="output-h1">The current agenda...<hr id="splitter"></h1>
</div>
<section id="output-section">
<div class="todo-div">
<h1 class="text-content">Mow the lawn</h1>
<button class="delete-btn">x</button>
<p class="date-p">mm/dd/yyyy</p>
</div>
<div class="todo-div">
<h1 class="text-content">Mow the lawn</h1>
<button class="delete-btn">x</button>
<p class="date-p">mm/dd/yyyy</p>
</div>
</section>
<script src="/toDo.js"></script>
</body>
</html>
There are really only rare cases where you want to manipulate the DOM through HTML. So using insertAdjacentHTML and innerHTML is most of the time not what you want to do.
Use createElement, appendChild and removeChild instead.
For the delete button, you can use event delegation, and find the todo div that corresponds to the button using closest.
Alternating coloring per row can be done with a CSS rule.
Using all this you will have a code like that:
"use strict";
const outputSection = document.querySelector("#output-section");
outputSection.innerHTML = "";
const writingArea = document.querySelector("#writing-area");
const publishBtn = document.querySelector(".default-btn");
const cutAndPrintFunc = function(e) {
e.preventDefault();
//take writing in and print it to the current agenda
// clear the writing area
if (writingArea.value != "") {
const date = new Date();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDay()).padStart(2, "0");
const year = date.getFullYear();
const hour = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
const AMorPM = date.getHours() > 12 ? "PM" : "AM";
const minute = String(date.getMinutes()).padStart(2, "0");
// create an actual div element using createElement
const todoItem = document.createElement('div')
// add the todo-div class to it
todoItem.classList.add('todo-div')
// here you can use innerHTML, but you still might want to
// avoid its usage in general
todoItem.innerHTML = `
<h1 class="text-content">${writingArea.value}</h1>
<button class="delete-btn">x</button>
<p class="date-p">${month}/${day}/${year} --- requested # ${hour}:${minute} ${AMorPM} </p>
`;
// append the created div element to the outputSection
outputSection.appendChild(todoItem);
writingArea.value = "";
}
};
//publish text by hitting enter or pressing the plus sign in textbox
publishBtn.addEventListener("click", cutAndPrintFunc);
// we attach an event listener on outputSection for click
outputSection.addEventListener("click", (evt) => {
// only handle the click if it happend on the delete button
if (evt.target.matches('.delete-btn')) {
evt.preventDefault();
// At this point the evt.target is the delete button the
// click happened on so you need search for the
// ascendant that represents the todo-div using closest
// and remove that element from outputSection
outputSection.removeChild(evt.target.closest('.todo-div'))
}
})
/* use the odd rule to style all odd todo-div elements */
.todo-div:nth-child(odd) {
background-color: #3ce815;
}
<!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" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Comfortaa&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="/style.css" type="text/css" />
<title>Griffin's ToDo List</title>
</head>
<body>
<header>
<h1>
Welcome to <em style="text-decoration: underline">Griffin's</em> To-Do List
</h1>
<div id="mini-flex-div">
<div class="ball" id="blue"> </div>
<div class="ball" id="orange"> </div>
<div class="ball" id="purple"> </div>
<p>What needs to be done today...</p>
<div class="ball" id="purple"> </div>
<div class="ball" id="orange"> </div>
<div class="ball" id="blue"> </div>
</div>
</header>
<main>
<div id="writer-div">
<form>
<input id="writing-area" type="text" rows="1" placeholder="Lets get this out of the way..." maxlength="50" spellcheck="true" autofocus>
<button class='default-btn'>+</button>
</form>
</div>
</main>
<div id="bottom-header">
<h1 id="output-h1">The current agenda...
<hr id="splitter">
</h1>
</div>
<section id="output-section">
<div class="todo-div">
<h1 class="text-content">Mow the lawn</h1>
<button class="delete-btn">x</button>
<p class="date-p">mm/dd/yyyy</p>
</div>
<div class="todo-div">
<h1 class="text-content">Mow the lawn</h1>
<button class="delete-btn">x</button>
<p class="date-p">mm/dd/yyyy</p>
</div>
</section>
<script src="/toDo.js"></script>
</body>
</html>
Unrelated to your problem:
input elements do not have a closing tag </input>
If you simply wish to remove the item from the list, start at the clicked button, use parentNode to find the "grand" parent (parent's parent) element, and remove, removeChild, the button's parent element:
// get all buttons and add a click event listener
document.querySelectorAll("button.delete-btn").forEach(btn => btn.addEventListener("click",
evt => {
// get the button's "grandparent", and remove the parent
evt.target.parentNode.parentNode.removeChild(evt.target.parentNode);
}
))
<!-- SAMPLE TO DO LIST -->
<section id="output-section">
<div class="todo-div" style="background-color: rgb(60, 232, 21);">
<h1 class="text-content">abc</h1>
<button class="delete-btn">x</button>
<p class="date-p" style="color: black;">06/00/2022 --- requested # 7:49 AM </p>
</div>
<div class="todo-div">
<h1 class="text-content">def</h1>
<button class="delete-btn">x</button>
<p class="date-p">06/00/2022 --- requested # 7:49 AM </p>
</div>
<div class="todo-div" style="background-color: rgb(60, 232, 21);">
<h1 class="text-content">ghi</h1>
<button class="delete-btn">x</button>
<p class="date-p" style="color: black;">06/00/2022 --- requested # 7:49 AM </p>
</div>
</section>
here is some improvements in your html and js file.
we provide each inserted div an id based on arrayOfText length so we can direct access id and used it with combine todo-div + id
and remove particular div from its own parent.
"use strict";
const outputSection = document.querySelector("#output-section");
outputSection.innerHTML = "";
const writingArea = document.querySelector("#writing-area");
const publishBtn = document.querySelector(".default-btn");
const deleteBtns = document.getElementsByClassName("delete-btn");
const allToDoDivs = document.getElementsByClassName("todo");
const arrayOfText = [];
const cutAndPrintFunc = function (e) {
e.preventDefault();
//take writing in and print it to the current agenda
// clear the writing area
if (writingArea.value != "") {
const date = new Date();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDay()).padStart(2, "0");
const year = date.getFullYear();
const hour = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
const AMorPM = date.getHours() > 12 ? "PM" : "AM";
const minute = String(date.getMinutes()).padStart(2, "0");
const indexAdd = (arrayOfText.length === 0) ? 0 : arrayOfText.length;
const template = `
<div class="todo todo-div${indexAdd}">
<h1 class="text-content">${writingArea.value}</h1>
<button class="delete-btn" onclick="removeTodoDiv(${indexAdd})">x</button>
<p class="date-p">${month}/${day}/${year} --- requested # ${hour}:${minute} ${AMorPM} </p>
</div>`;
arrayOfText.push(template);
outputSection.insertAdjacentHTML("beforeend", template);
writingArea.value = "";
Array.from(allToDoDivs).forEach((el, ind) => {
if (ind % 2 === 0) {
el.style.backgroundColor = "#3ce815";
el.lastElementChild.style.color = "black";
}
//-----this does not work
// Array.from(allToDoDivs)[
// allToDoDivs.length - 1
// ].children[1].addEventListener("click", () => {
// console.log(this);
// // arrayOfText.pop(this);
// // outputSection.innerHTML = arrayOfText.join("");
// });
});
}
};
//publish text by hitting enter or pressing the plus sign in textbox
publishBtn.addEventListener("click", cutAndPrintFunc);
function removeTodoDiv(index) {
const findDiv = document.getElementsByClassName('todo-div' + index)[0];
findDiv.parentNode.removeChild(findDiv);
}
<!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" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Comfortaa&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="/style.css" type="text/css" />
<title>Griffin's ToDo List</title>
</head>
<body>
<header>
<h1>
Welcome to <em style="text-decoration: underline">Griffin's</em> To-Do
List
</h1>
<div id="mini-flex-div">
<div class="ball" id="blue"> </div>
<div class="ball" id="orange"> </div>
<div class="ball" id="purple"> </div>
<p>What needs to be done today...</p>
<div class="ball" id="purple"> </div>
<div class="ball" id="orange"> </div>
<div class="ball" id="blue"> </div>
</div>
</header>
<main>
<div id="writer-div">
<form>
<input id="writing-area" type="text" rows="1" placeholder="Lets get this out of the way..." maxlength="50"
spellcheck="true" autofocus></input>
<button class='default-btn'>+</button>
</form>
</div>
</main>
<div id="bottom-header">
<h1 id="output-h1">The current agenda...
<hr id="splitter">
</h1>
</div>
<section id="output-section">
<!-- <div class="todo-div">
<h1 class="text-content">Mow the lawn</h1>
<button class="delete-btn">x</button>
<p class="date-p">mm/dd/yyyy</p>
</div>
<div class="todo-div">
<h1 class="text-content">Mow the lawn</h1>
<button class="delete-btn">x</button>
<p class="date-p">mm/dd/yyyy</p>
</div> -->
</section>
<script src="./index.js"></script>
</body>
</html>

How to show element created in javascript as child?

I can successfully add div to my ".list-group" div and localstorage, they work dynamically. But these elements do not appear to be offspring of its container. If you try it in your own browser, you will see that it returns a null value. Why don't my list items appear as kids? And how can I make it appear Child. Thank's adavance for your answers. Codepen: https://codepen.io/BerkayAkgurgen/pen/xxEmQLo
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");
let alert = document.getElementById("alertID");
eventListeners();
console.log(todoList.firstElementChild);
//Event Listeners
function eventListeners() {
secondCardBody.addEventListener("click", deleteTodo);
form.addEventListener("submit", addTodo);
document.addEventListener("DOMContentLoaded", loadAllTodosToUI);
filter.addEventListener("keyup", filterTodos);
clearButton.addEventListener("click",clearAllTodos);
}
// Todo Ekleme
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") {
showAlert("danger", "Lütfen bir todo giriniz");
} else {
showAlert("success", "Giriş Başarılı");
addTodoToUI(newTodo);
addTodoToStorage(newTodo);
}
e.preventDefault();
}
function addTodoToUI(newTodo) {
const listItem = document.createElement("li");
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";
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
todoList.appendChild(listItem);
todoInput.value = "";
}
// Alert
function showAlert(type, message) {
let = alert;
if (alert == null) {
alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.id = "alertID";
alert.textContent = message;
firstCardBody.appendChild(alert);
alert.style.marginTop = "1rem";
} else {
alert.className = `alert alert-${type}`;
alert.textContent = message;
document.getElementById("alertID").style.display = 'block';
}
setTimeout (function myFunction2() {
document.getElementById("alertID").style.display = 'none';
}, 1000)
};
// Todo Storage Ekleme
function addTodoToStorage(newTodo) {
let todos = getTodosFromStorage();
todos.push(newTodo);
localStorage.setItem("todos", JSON.stringify(todos));
}
function getTodosFromStorage() { // Storage'den Todoları Almak
let todos;
if (localStorage.getItem("todos") === null) {
todos = [];
} else {
todos = JSON.parse(localStorage.getItem("todos"));
}
return todos;
}
// Sayfa Yüklendiğinde Storage Yükleme
function loadAllTodosToUI() {
let todos = getTodosFromStorage();
todos.forEach(function (todo) {
addTodoToUI(todo);
})
}
// Todo Silme
function deleteTodo(e) {
if (e.target.className === "fa fa-remove") {
e.target.parentElement.parentElement.remove();
}
}
// Todo Filtreleme
function filterTodos(e) {
const filterValue = e.target.value.toLowerCase();
const listItems = document.querySelectorAll(".list-group-item");
listItems.forEach(function (listItem) {
const text = listItem.textContent.toLowerCase();
if (text.indexOf(filterValue) === -1) {
// Bulamadı
listItem.setAttribute("style", "display : none !important");
} else {
listItem.setAttribute("style", "display : block");
}
});
}
// Tüm Todoları Silme
function clearAllTodos(e) {
if (confirm("Tümünü Silmek istediğinize Emin Misiniz?")) {
// Arayüzden Todoları Temizleme
// todoList.innerHTML = ""; // Yavaş Yöntem
}
}
console.log(todoList.firstElementChild);
<!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" />
<link rel="stylesheet" href="berkay.css">
<title>Todo List</title>
</head>
<body>
<div class="container" id="bal" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body bdy">
<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"
autocomplete="off" tabindex="1" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body 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"
tabindex="2" />
</div>
</div>
<hr />
<ul class="list-group"></ul>
<hr />
<a id="clear-todos" class="btn btn-dark" href="#">Tüm Taskları Temizleyin</a>
</div>
</div>
</div>
<div class="box" style="display: none;"></div>
<div class="box2" style="display: none;"></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>

How can I run Bootstrap Alert multiple times?

I am using the Bootstrap alert system, but I encountered a problem. My Alert appears when the button is pressed, and then the setTimeout function works and my alert does not appear after 1 second. But the problem is here, the alert part does not appear again when I make a successful or incorrect login. I want my alert to appear on every successful or incorrect login. Thanks advance for your answers. (ı don't want Jquery, only Vanilla JavaScript.) Codepen.io: https://codepen.io/BerkayAkgurgen/pen/xxEmQLo (All Code)
function showAlert(type, message) {
if (alert == null) {
alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.id = "alertID";
alert.textContent = message;
firstCardBody.appendChild(alert);
alert.style.marginTop = "1rem";
} else {
alert.className = `alert alert-${type}`;
alert.textContent = message;
}
setTimeout(function myFunction2() {
document.getElementById("alertID").style.display = 'none';
}, 1000)
};
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")[0];
const clearButton = document.querySelector("#clear-todos")[0];
let alert = document.getElementById("alertID");
eventListeners();
//Event Listeners
function eventListeners() {
secondCardBody.addEventListener("click", deleteTodo);
form.addEventListener("submit", addTodo);
document.addEventListener("DOMContentLoaded", loadAllTodosToUI);
}
// Todo Ekleme
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") {
showAlert("danger", "Lütfen bir todo giriniz");
} else {
showAlert("success", "Giriş Başarılı");
addTodoToUI(newTodo);
addTodoToStorage(newTodo);
}
e.preventDefault();
}
function addTodoToUI(newTodo) {
const listItem = document.createElement("li");
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";
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
todoList.appendChild(listItem);
todoInput.value = "";
}
// Alert
function showAlert(type, message) {
if (alert == null) {
alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.id = "alertID";
alert.textContent = message;
firstCardBody.appendChild(alert);
alert.style.marginTop = "1rem";
} else {
alert.className = `alert alert-${type}`;
alert.textContent = message;
}
setTimeout(function myFunction2() {
document.getElementById("alertID").style.display = 'none';
}, 1000)
};
// Todo Storage Ekleme
function addTodoToStorage(newTodo) {
let todos = getTodosFromStorage();
todos.push(newTodo);
localStorage.setItem("todos", JSON.stringify(todos));
}
function getTodosFromStorage() { // Storage'den Todoları Almak
let todos;
if (localStorage.getItem("todos") === null) {
todos = [];
} else {
todos = JSON.parse(localStorage.getItem("todos"));
}
return todos;
}
// Sayfa Yüklendiğinde Storage Yükleme
function loadAllTodosToUI() {
let todos = getTodosFromStorage();
todos.forEach(function(todo) {
addTodoToUI(todo);
})
}
// Todo Silme
function deleteTodo(e) {
if (e.target.className === "fa fa-remove") {
e.target.parentElement.parentElement.remove();
}
}
<!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" />
<link rel="stylesheet" href="berkay.css">
<title>Todo List</title>
</head>
<body>
<div class="container" id="bal" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body bdy">
<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" autocomplete="off" tabindex="1" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body 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" tabindex="2" />
</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>
<div class="box" style="display: none;"></div>
<div class="box2" style="display: none;"></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>
Add an extra line to your alert code:
......
} else {
alert.className = `alert alert-${type}`;
alert.textContent = message;
document.getElementById("alertID").style.display = 'initial';
}
More info here

input field not resetting

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()......

Categories

Resources