When argument in method is allocated in javascript? - 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>

Related

How to add SweetAlert2 in If statement?

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>

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>

Cancelling onSubmit with JS Field Validation

I am trying to validate length of password and display a warning message but message is temporary.
I have tried using the onsubmit attribute with the submit button but it still doesn't work.
function validate()
{
var pw = document.getElementById("password").value
if(pw.length<8)
{
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
}
}
<!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>
<form action="">
<input type="text" id="password"/>
<br/>
<span id="span" style="color:red;"></span>
<button onclick="validate()">Submit</button>
</form>
</body>
</html>
There were a few things fixed below:
Pass the event to your validate(), like this: onclick="validate(event)".
Cancel the regular event that happens with onsubmit by means of Event.preventDefault() and return false, but the former is much more important.
Notice what you see below when password is too short and when password is long enough:
function validate(ev)
{
var pw = document.getElementById("password").value
if(pw.length<8)
{
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>";
ev.preventDefault();
return 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>Document</title>
</head>
<body>
<form action="">
<input type="text" id="password"/>
<br/>
<span id="span" style="color:red;"></span>
<button onclick="validate(event)">Submit</button>
</form>
</body>
</html>
document.querySelector('form').addEventListener('submit', validate);
function validate(event) {
event.preventDefault();
const form = new FormData(event.target);
const password = form.get('password').trim();
if (password.length < 8) {
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
return;
}
event.target.submit();
}
<!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>
<form action="">
<input name="password" type="text" id="password"/>
<br/>
<span id="span" style="color:red;"></span>
<button type="submit">Submit</button>
</form>
</body>
</html>
Your script should look something like this:
document.querySelector('form').addEventListener('submit', validate);
function validate(event) {
event.preventDefault();
const form = new FormData(event.target);
const password = form.get('password').trim();
if (password.length < 8) {
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
return;
}
event.target.submit();
}
I put the .trim() because it is usually a good idea to trim the inputs.
Consider this if you are using the inline attributes:
"You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient. " This is from the mdn documentation -> https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
var ssn = document.getElementById("ssn");
var current = document.getElementById("current");
ssn.oninput = function(event) {
current.textContent = ssn.value;
}
<!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>
<form action="">
<label for="ssn">password:</label>
<input type="password" id="ssn" inputmode="numeric" minlength="9" maxlength="12"
pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}"
required autocomplete="off">
<br>
<label for="ssn">Value:</label>
<span id="current"></span>
<span id="span" style="color:red;"></span>
<button onclick="validate()">Submit</button>
</form>
</body>
</html>
You could use the submit event on the form and return a status (boolean) on whether or not to let the request go through. (This is what is usually used for form validation.)
<form action="" onsubmit="return validate()">
function validate()
{
var pw = document.getElementById("password").value
if(pw.length<8)
{
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>";
return false;
}
return true;
}
If the function returns true, it means the form is valid and the submission will go through.
If it returns false, it will show the error message and will not submit the form.

Cannot Read the property of addEventListener of null

I keep getting this error: Uncaught TypeError: Cannot read property 'addEventListener' of null. I looked at other posts that had similar issues but I guess my level of understanding for Javascript is not proficient enough to understand the proposed solutions given. Can someone help me?
Here is my Javascript code:
const multButton = document.getElementById('multiply');
const divideButton = document.getElementById('divide');
const firstNum = document.getElementById('firstNum')
const secondNum = document.getElementById('secondNum')
function multiplyNum(first, second){
const sum = first * second;
return alert(sum);
}
function divideNum(first, second){
const sum = first/second;
return alert(sum);
}
multButton.addEventListener('click', multiplyNum)
divideButton.addEventListener('click', divideNum)
Here is my HTML:
<!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>Document</title>
</head>
<body>
Calculator
<div>
<form action="get">
1st Number: <input type="number" id="firstNum" name="firstNum"> <br>
2nd Number: <input type="number" id="secondNum" name="secondNum"> <br>
<button type="submit" id="multiply">Multiply</button>
<button type="submit" id="divide">Divide</button>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
What happens here is when you click on a button inside a form, it invokes the forms default submit method. I've moved the buttons outside the form tag so that it won't invoke the submit method. Thus we won't be redirected to another page on submission. Earlier we got redirected, that's why the dom elements where unavailable.
The HTMl:
<!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>Document</title>
</head>
<body>
Calculator
<div>
<form action="get">
1st Number: <input type="number" id="firstNum" name="firstNum" /> <br />
2nd Number: <input type="number" id="secondNum" name="secondNum" />
<br />
</form>
<button id="multiply">Multiply</button>
<button id="divide">Divide</button>
</div>
<script src="script.js"></script>
</body>
</html>
The script
const multButton = document.getElementById("multiply");
const divideButton = document.getElementById("divide");
const firstNum = document.getElementById("firstNum");
const secondNum = document.getElementById("secondNum");
function multiplyNum() {
const sum = firstNum.value * secondNum.value;
return alert(sum);
}
function divideNum() {
const sum = firstNum.value / secondNum.value;
return alert(sum);
}
multButton.addEventListener("click", multiplyNum);
divideButton.addEventListener("click", divideNum);
Either multButton is null because an element with the "id" "multiply" doesn't exist or divideButton is null because an element with the "id" "divide" doesn't exist (or both don't exist).
Your code that you posted is fine (although in your form tag it should be method='get' and not action='get').
The following is a modified version of your code that I ran:
<!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>Document</title>
</head>
<body>
Calculator
<div>
<form method='get'>
1st Number: <input type="number" id="firstNum" name="firstNum"> <br>
2nd Number: <input type="number" id="secondNum" name="secondNum"> <br>
<button type="submit" id="multiply">Multiply</button>
<button type="submit" id="divide">Divide</button>
</form>
</div>
<script>
const multButton = document.getElementById('multiply');
const divideButton = document.getElementById('divide');
const firstNum = document.getElementById('firstNum')
const secondNum = document.getElementById('secondNum')
multButton.addEventListener('click', function() {
alert('Multiply');
})
divideButton.addEventListener('click', function() {
alert('Divide');
})
</script>
</body>
</html>

Categories

Resources