How to add SweetAlert2 in If statement? - javascript

I'm trying to get a simple alert that will alert if you leave it blank and hit the enter key on to-do list by using SweetAlert2 with JavaScript.
I've added some codes that was on document but it's not working.
I'm not sure how to code it in if statement.
Any help is appreciated!
Here's what I did.
I followed the usage on https://sweetalert2.github.io/
So I installed,
npm install sweetalert2
index.html
<!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>to-do App</title>
</head>
<body>
<header>
<form id="new-task-form">
<input
type="text"
id="new-task-input"
placeholder="What's your plans?"
/>
<input type="submit" id="new-task-submit" value="ADD" />
</form>
</header>
<main>
<section class="task-list">
<h2>Tasks</h2>
<div id="tasks"></div>
</section>
</main>
<script src="index.js"></script>
</body>
</html>
main.js
window.addEventListener("load", () => {
const form = document.querySelector("#new-task-form");
const input = document.querySelector("#new-task-input");
const list_el = document.querySelector("#tasks");
form.addEventListener("submit", (e) => {
e.preventDefault();
const task = input.value;
const Swal = require('sweetalert2') // Added this!
if (!task) {
Swal.fire("Whoop! Forgot to add something?"); // Added this!
return;
}
const task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
task_el.appendChild(task_content_el);
const task_input_el = document.createElement("input");
task_input_el.classList.add("text");
task_input_el.type = "text";
task_input_el.value = task;
task_input_el.setAttribute("readonly", "readonly");
task_content_el.appendChild(task_input_el);
const task_actions_el = document.createElement("div");
task_actions_el.classList.add("actions");
const task_edit_el = document.createElement("button");
task_edit_el.classList.add("edit");
const task_delete_el = document.createElement("button");
task_delete_el.classList.add("delete");
task_delete_el.innerHTML = "Delete";
task_actions_el.appendChild(task_edit_el);
task_actions_el.appendChild(task_delete_el);
task_el.appendChild(task_actions_el);
list_el.appendChild(task_el);
input.value = "";
task_edit_el.addEventListener("click", () => {
if (task_edit_el.innerText.toLowerCase() === "edit") {
task_input_el.removeAttribute("readonly");
task_input_el.focus();
task_edit_el.innerText = "Save";
} else {
task_input_el.setAttribute("readonly", "readyonly");
task_edit_el.innerText = "Edit";
}
});
task_delete_el.addEventListener("click", () => {
list_el.removeChild(task_el);
});
});
});

Just import sweetalert by <script>
index.html
<!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>to-do App</title>
</head>
<body>
............
<script src="node_modules/sweetalert2/dist/sweetalert2.all.min.js"> </script>
</body>
</html>

Related

Textfield Input Value Returning Null

I'm working on an app that makes fetch calls to a dictionary API based on the user's input. The problem is, I can't seem to get the input value from the search bar. Currently, all that's being logged to the console is an empty string. I currently have my code inside of a DOMContentLoaded event listener. When I take my code out of the DOMContentLoaded function, I am getting a null value returned. This is incredibly straightforward but I can't seem to figure out what is getting muddled here. Here is the code;
window.addEventListener('DOMContentLoaded', () => {
const searchBar = document.getElementById('search-bar');
const userInput = searchBar.value;
const searchButton = document.getElementById('search-button');
const test = () => console.log(userInput);
searchButton.addEventListener('click', test);
});
<!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">
<script src="app.js"></script>
<title>Dictionary</title>
</head>
<body>
<h1>Dictionary</h1>
<input type="text" id="search-bar" placeholder="Find a definition"/>
<button id="search-button">Search</button>
<div id="results-area">
</div>
</body>
</html>
Thanks for the help.
The issue was you're getting always the first value of input which is empty, to get the new value call searchBar.value on the click of button.
window.addEventListener('DOMContentLoaded', () => {
const searchBar = document.getElementById('search-bar');
const searchButton = document.getElementById('search-button');
const getInputValue = () => {
let userInput = searchBar.value;
console.log(userInput);
}
searchButton.addEventListener('click', getInputValue);
});
<!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">
<script src="app.js"></script>
<title>Dictionary</title>
</head>
<body>
<h1>Dictionary</h1>
<input type="text" id="search-bar" placeholder="Find a definition" />
<button id="search-button">Search</button>
<div id="results-area">
</div>
</body>
</html>

I am trying to use an user HTML input to change a javascript object value

I am trying to use HTML 'input' to change apiData.id value. I'm new to javascript and not sure if this is correct. Any suggestions would be greatly appreciated.
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
const newId = apiData.id;
function eventController(event) {
newId = event.target.value;
}
input.addEventListener('change', eventController, false);
<!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>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>
<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>
newId is const, so you cannot assign it with a new value after it has been declared.
But even if you could (and you can, by making it a variable), that would not affect apiData.id, as newId is assigned with the value of apiData.id, but they are not bound together.
You should just assign apiData.id directly with a new value:
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
// const newId = apiData.id;
function eventController(event) {
apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);
<!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>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>
<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>

can't select element with dom, after creating that element with other function - appendChild

How i'm supposed to select my element that have been created by function. First function is working well, but while i'm trying to select the element that been created in that function, it doesn't work
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function () {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
body.appendChild(c);
});
document.querySelector("p").addEventListener("click", function () {
console.log("Hi");
});
<!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>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="lop">s</div>
<div class="body"></div>
<script src="script.js"></script>
</body>
</html>
That's because you are attempting to attach a click event to your paragraph tag before its ever been added to the DOM.
You will need to move this new event listener inside of your onclick and after you append it to your .body div.
Example:
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function () {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
body.appendChild(c);
document.querySelector("p").addEventListener("click", function () {
console.log("Hi");
});
});
As requested, here is how you could just split some of this out to be its own methods for clarity. Feel free to use your own style as its just an example:
const onClickLop = (e) => {
const el = document.createElement("p");
const bodyDiv = document.querySelector(".body");
el.appendChild(document.createTextNode("lopas"));
bodyDiv.appendChild(el);
el.addEventListener("click", onClickLopas);
};
const onClickLopas = (e) => {
console.log("Hi");
});
document.querySelector(".lop").addEventListener("click", onClickLop);
Problem:
You create the p element at the moment when you click on .lop
You try to add the event listener at the page load. At this point there is no p tag at all.
Solution:
Add the event listener after you created the p tag.
You could also use the reference c instead of querySelector.
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function() {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
body.appendChild(c);
c.addEventListener("click", function() {
console.log("Hi");
});
});
<!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>Document</title>
</head>
<body>
<div class="lop">s</div>
<div class="body"></div>
</body>
</html>
The code to add the event listener for the p element is executing before your code that creates it. Move the event handler into the first function so that it isn't triggered until the element is created and added to the document. However, that will mean that each time you click the first element, a new p will be created with its own handler (separate question/answer).
Also, by doing that you can consolidate some code.
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function () {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
c.addEventListener("click", function () {
console.log("Hi");
});
body.appendChild(c);
});
<!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>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="lop">s</div>
<div class="body"></div>
<script src="script.js"></script>
</body>
</html>

When argument in method is allocated in javascript?

Can you let me know when method(function in a function)'s argument is allocated?
if the arguments in method(in a function)is allocated when they are declared, there's no value of USERNAME.value when it is declared.
but If I put Stored Name as a argument of greeting in function store(which is call back function used for event),null comes out even if I put my user name on in input box.
However, If I put USERNAME.value, it works properly.
This is my js code,
const USERNAME = document.getElementById("username");
const Form = document.querySelector("form");
const HIDDEN = "hidden";
const h2 = document.querySelector("h2");
const KEY = "username";
function greeting(who) {
h2.innerText = `Hello, ${who}`;
h2.classList.remove(HIDDEN);
}
function store(event) {
event.preventDefault();
localStorage.setItem(KEY, USERNAME.value);
Form.classList.add(HIDDEN);
greeting(StoredName);
}
const StoredName = localStorage.getItem(KEY);
if (StoredName == null) {
Form.classList.remove(HIDDEN);
Form.addEventListener("submit", store);
} else {
greeting(StoredName);
}
and this is my html code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="practice.css">
<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>Document</title>
</head>
<body>
<h2 class="hidden"></h2>
<form action="" class="hidden">
<input type="text" name="" id="username">
<input type="submit" value="">
</form>
<script src="practice.js"></script>
</body>
</html>

How do I change color of text in client side javascript?

I am adding a list item to my ul from an input textarea. How do I change it's color based on if it's a palindrome or not? Below is the js file of my code.
function isPalindrome(text){
return text == text.split('').reverse().join('');
}
const staticForm = document.getElementById('static-form');
let myUl = document.getElementById('list');
const textarea = document.getElementById('text');
staticForm.addEventListener('submit', (event) => {
event.preventDefault();
if (isPalindrome(text)==true) textarea.style.color='red';
else textarea.style.color='blue';
let li = document.createElement('li');
li.innerHTML = textarea.value;
myUl.appendChild(li);
myForm.reset();
textarea.focus();
const result = isPalindrome(textarea)
});
HTML:
<main>
<form id='static-form' method="POST" class="new-post-form">
<textarea id='text' name='phrase'>
Attempt here
</textarea>
<input class="sub-button" type="submit" name="submit" value="Submit" />
</form>
<ul id='list'></ul>
</main>
I know that writing textarea.style.color does not work, what is the best way to achieve this?
function isPalindrome(text) {
return text === text.split("").reverse().join("");
}
const staticForm = document.getElementById("static-form");
let myUl = document.getElementById("list");
const textarea = document.getElementById("text");
const submitBtn = document.getElementById("submit");
submitBtn.addEventListener("click", (event) => {
const text = document.getElementById("text").value;
textarea.style.color = isPalindrome(text) ? "red" : "blue";
let li = document.createElement("li");
li.innerHTML = textarea.value;
myUl.appendChild(li);
textarea.focus();
const result = isPalindrome(textarea);
});
<!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>Static Template</title>
</head>
<body>
<main>
<form id="static-form" method="POST" class="new-post-form">
<textarea id="text" name="phrase">sample text</textarea
>
<input
class="sub-button"
id="submit"
type="button"
name="submit"
value="Submit"
/>
</form>
<ul id="list"></ul>
</main>
</body>
</html>
function changeTextareaColor(){
const textarea = document.getElementById("textarea");
if (textarea) {
textarea.style.color = "red";
}
}
<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>Static Template</title>
</head>
<body>
<textarea id="textarea">
This is a static template, there is no bundler or bundling involved!
</textarea>
<button onclick="changeTextareaColor()">change color</button>
<script>
</script>
</body>
</html>
I modify your code a little bit. I hope It will work.

Categories

Resources