This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I have a question when writing js. I define a toys variable in the beginning of the file, it works when I do it in console in chrome, but within the js file, i got an error when trying to use it, it says toys is null.
index.js file:
let addToy = false
let toys = document.getElementById("toy-collection")
document.addEventListener("DOMContentLoaded", ()=>{
const addBtn = document.querySelector('#new-toy-btn')
const toyForm = document.querySelector('.container')
addBtn.addEventListener('click', () => {
// hide & seek with the form
addToy = !addToy
if (addToy) {
toyForm.style.display = 'block'
} else {
toyForm.style.display = 'none'
}
})
fetchToys()
})
function fetchToys(){
fetch("http://localhost:3000/toys")
.then(resp=>resp.json())
.then(json=>addJsonToBlock(json))
}
function addJsonToBlock(json){
for (const toy of json){
toys.innerHTML += `<div class='card'>${toy.name}</div>`
}
}
index.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Toy Tale</title>
<script type="text/javascript" src="src/index.js"></script>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<div id="toy-header">
<img
src="https://fontmeme.com/permalink/180719/67429e6afec53d21d64643101c43f029.png"
alt="toy-header"
/>
</div>
<div class="container">
<form class="add-toy-form">
<h3>Create a toy!</h3>
<input
type="text"
name="name"
value=""
placeholder="Enter a toy's name..."
class="input-text"
/>
<br />
<input
type="text"
name="image"
value=""
placeholder="Enter a toy's image URL..."
class="input-text"
/>
<br />
<input
type="submit"
name="submit"
value="Create New Toy"
class="submit"
/>
</form>
</div>
<p style="text-align:center">
Andy needs your help! <button id="new-toy-btn">Add a new toy!</button>
</p>
<div id="toy-collection"></div>
</body>
</html>
Move your script to the bottom of body before the closing </body> tag.
<script type="text/javascript" src="src/index.js"></script>
It's not working because it's loaded before the DOM has loaded. When you include it at the end, then it loads after the DOM has loaded.
Related
This question already has answers here:
Why is document.write considered a "bad practice"?
(17 answers)
Best way to output Javascript?
(3 answers)
Closed 29 days ago.
note new to JavaScript
when clicking the button to write out the text from my input box it prints out the text but deletes everything else
JavaScript code
let = Text
document.getElementById("Button7").onclick = function () {
Text = document.getElementById("myText").value;
document.write(Text)
}
HTML code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" id="myText" placeholder="enter text"> <br>
<button id="Button7">enter</button>
<script type="text/javascript" src="index.js"></script>
<h1>my first website test</h1>
</body>
</html>
You can display the value of the input in a <p> element by setting its textContent. Do not use document.write.
document.getElementById("Button7").addEventListener('click', function() {
document.getElementById("result").textContent = document.getElementById("myText").value;
});
<input type="text" id="myText" placeholder="enter text"> <br>
<button id="Button7">enter</button>
<p id="result"></p>
The JavaScript function to change the image source is not working.
This is my code:
function eye() {
fun();
fun1();
}
function fun() {
if (document.getElementById("password").type == "text") {
document.getElementById("password").type = "password";
} else if (document.getElementById("password").type == "password") {
document.getElementById("password").type = "text";
}
}
function fun1() {
if (document.getElementById("eye").src == "eyec.png") {
document.getElementById("eye").src = "eye.png";
} else if (document.getElementById("eye").src == "eye.png") {
document.getElementById("eye").src = "eyec.png";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="login.css">
</head>
<body>
<header>
<button class="menu_btn" onclick="start()">
<img class="menu" src="menu.png" alt="menu" id="icon-menu">
</button>
<img class="logo" src="logo.png" alt="logo" />
<header/>
<form action="login-ctrl.php" method="post">
<div class="log-form">
<label for="email">Email:<br><input type="email" class="email" placeholder="input email...." name="email"/></label><br>
<label class="label" for="password">Password:<br><input type="password" id="password" class="password" placeholder="input password...." name="password"/><div onclick="eye()" class="eye-btn"><img src="eye.png" id="eye"></div></label>
<button class="log-but" type="submit" name="submit">login</button>
</div>
</form>
</body>
<script src="index.js"></script>
<script src="login.js"></script>
</html>
I have tried writing the functions in different scripts, but it still didn't work, it is supposed to change the source of the image to another when clicked first then back when clicked again.
When you read the parameter document.getElementById("eye").src, it returns the complete file path, like file:///C:/Users/john/Documents/eye.png. You can replace it with getAttribute('src') method:
function eye() {
fun();
fun1();
}
function fun() {
if (document.getElementById("password").type == "text") {
document.getElementById("password").type = "password";
} else if (document.getElementById("password").type == "password") {
document.getElementById("password").type = "text";
}
}
function fun1() {
if (document.getElementById("eye").getAttribute("src") == "eyec.png") {
document.getElementById("eye").src = "eye.png";
} else if (document.getElementById("eye").getAttribute("src") == "eye.png") {
document.getElementById("eye").src = "eyec.png";
}
}
Here is a simplified version that doesn't require all of the extra javascript, just a few lines of javascript and some CSS.
For this answer, I'm using javascript to detect the click and change the type.
From there, in CSS I'm changing the button's background based on type of .password. I changed the HTML so that the div is a button and it doesn't have an inline onclick nor an img tag in side.
In CSS, you can easily give the button different width/height and change the background to an image.
let pw = document.querySelector("#password");
let eye = document.querySelector(".eye-btn");
eye.addEventListener("click",(e) => {
pw.type = (pw.type == "password") ? "text" : "password";
});
.eye-btn{
width:15px;
height:15px;
outline:0;
border:0;
padding:0;margin:0;
}
.password[type='password'] ~ .eye-btn{
background:green;
}
.password[type='text'] ~ .eye-btn{
background:blue;
}
<input type="password" id="password" class="password" placeholder="input password...." value="Text to see type change" name="password"/><button type="button" class="eye-btn"></button>
The following snippet should do what you want. Even though we are not using jQuery, we should embrace its fundamental idea: "write less, do more!". This means: avoid using ids as CSS selectors and use class names instead. This way we can potentially apply a single function on many situations.
I also changed the event attachment of your click-event handler function eye() (now called showHide) - and the function itself - in some more ways, check it out below:
function showHide(ev) {
const img=ev.target, pw=img.closest(".eye-btn").previousElementSibling,
hidden=pw.type==="password";
pw.type=hidden?"text":"password";
img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/"+(hidden?"c/cf/OOjs_UI_icon_eye.svg/20px-OOjs_UI_icon_eye.svg.png":"7/79/OOjs_UI_icon_eyeClosed.svg/20px-OOjs_UI_icon_eyeClosed.svg.png");
}
document.querySelectorAll(".eye-btn img").forEach(img=>img.addEventListener("click",showHide));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="login.css">
</head>
<body>
<header>
<button class="menu_btn" onclick="start()">
<img class="menu" src="menu.png" alt="menu" id="icon-menu">
</button>
<img class="logo" src="logo.png" alt="logo" />
<header/>
<form action="login-ctrl.php" method="post">
<div class="log-form">
<label for="email">Email:<br><input type="email" class="email" placeholder="input email...." name="email"/></label><br>
<label class="label" for="password">Password:<br><input type="password" id="password" class="password" placeholder="input password...." name="password"/><div class="eye-btn"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/OOjs_UI_icon_eyeClosed.svg/20px-OOjs_UI_icon_eyeClosed.svg.png"></div></label>
<button class="log-but" type="submit" name="submit">login</button>
</div>
</form>
</body>
<script src="index.js"></script>
<script src="login.js"></script>
</html>
The "relative DOM navigation" from the clicked image img to the password input field pw might be noteworthy: pw=img.closest(".eye-btn").previousElementSibling. First I move up to the closest parent element being of class "eye-btn". From there I move back to the previous element sibling (this will skip any line breaks, spaces or other text nodes in between the elements).
This question already has answers here:
What's the fastest way to convert String to Number in JavaScript?
(10 answers)
Closed 2 years ago.
function convertion() {
let inputValue = number(document.getElementById('firstValue').value);
let result = document.getElementById('secondValue');
result.innerHTML = inputValue * 10;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body>
<main>
<label for="firstValue">dm: </label>
<input id="firstValue" type='number'>
<button onclick="convertion()">
CONVERT
</button>
<br/>
<br/>
<label for="secondValue">cm: </label>
<input id="secondValue" readonly>
</main>
</body>
</html>
This is a dm-cm converter I don't know why it doesn't work. I think there's an error in the script.
I also don't know how to use the number function in this line:
let inputValue = number(document.getElementById('firstValue').value)
input boxes don't have innerHTML use value instead
function convertion() {
let inputValue = document.getElementById('firstValue').value;
console.log(inputValue);
let result = document.getElementById('secondValue');
result.value = inputValue * 10;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body>
<main>
<label for="firstValue">dm: </label>
<input id="firstValue" type='number' onchange="convertion()">
CONVERT
</button>
<br/>
<br/>
<label for="secondValue">cm: </label>
<input id="secondValue" readonly>
</main>
</body>
</html>
JavaScript codes and HTML codes
I'm trying to put a generated value of the qr code a input text to be save in my SQLite database can't pust the darn value of the qr code
var resultDiv;
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#startScan").
addEventListener("touchend", startScan, false);
resultDiv = document.querySelector("#results");//works in <p id="results"></p>
resultDiv = document.querySelector('#text4');//wont work at all <input id="text4" type="text" placeholder="Book Info"/>
}
function startScan() {
cordova.plugins.barcodeScanner.scan(
function (result) {
var s = result.text.split('|');
result.format;
result.cancelled;
resultDiv.innerHTML = s;
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
JavaScript codes and HTML codes
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>qrBorrowers</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<nav>
<div class="topnav">
Add
Borrow
Return
QR code
</div>
</nav>
<Label>
<h1> Borrow a Book </h1>
</Label>
<div class="borrow">
<input id="text1" type="text" placeholder="Borrower Number" onfocus="this.value=''"/>
<input id="text2" type="text" placeholder="Borrower Last Name" onfocus="this.value=''" />
<input id="text3" type="text" placeholder="Borrower First Name" onfocus="this.value=''" />
<input id="text4" type="text" placeholder="Book Info"/>
<input id="text6" type="date" placeholder="Date Borrowed" />
<br>
</div>
<div class="borrow">
<p id="results"></p>
<button id="startScan">Start Scan</button>
<button id="savedb">Save </button>
</div>
<script type="text/javascript" src="js/scanQR.js"></script>
</body>
</html>
With inner HTML it will not going to save your generated QR code to input box. You need to change the innerHTML to value to save the value in input box such that you can use that when form submit as value to save in database.
var resultDiv;
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#startScan").
addEventListener("touchend", startScan, false);
resultDiv = document.querySelector("#results");//works in <p id="results"></p>
resultDiv = document.querySelector('#text4');//wont work at all <input id="text4" type="text" placeholder="Book Info"/>
}
function startScan() {
cordova.plugins.barcodeScanner.scan(
function (result) {
var s = result.text.split('|');
result.format;
result.cancelled;
resultDiv.value = s;
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
JavaScript codes and HTML codes
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>qrBorrowers</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<nav>
<div class="topnav">
Add
Borrow
Return
QR code
</div>
</nav>
<Label>
<h1> Borrow a Book </h1>
</Label>
<div class="borrow">
<input id="text1" type="text" placeholder="Borrower Number" onfocus="this.value=''"/>
<input id="text2" type="text" placeholder="Borrower Last Name" onfocus="this.value=''" />
<input id="text3" type="text" placeholder="Borrower First Name" onfocus="this.value=''" />
<input id="text4" type="text" placeholder="Book Info"/>
<input id="text6" type="date" placeholder="Date Borrowed" />
<br>
</div>
<div class="borrow">
<p id="results"></p>
<button id="startScan">Start Scan</button>
<button id="savedb">Save </button>
</div>
<script type="text/javascript" src="js/scanQR.js"></script>
</body>
</html>
To save the value in input box should not use "resultDiv.innerHTML = s;"
Rather you should use "resultDiv.value = s" which will save your code to input box which you can use to save in SQLite Database.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed last year.
A small Javascript function to capitalize the contents of a text fields is as follows:
<html>
<head>
<title>capitalize</title>
</head>
<body>
<input type="text" id="uname" length="20" /><br />
<input type="submit" id="submit" value="submit" />
<script>
document.getElementById("submit").addEventListener("click",eve);
function eve(){
var uname = document.getElementById("uname").value;
uname = uname.toUpperCase();
document.getElementById("uname").value=uname;
}
</script>
</body>
</html>
Now, this is working normally, but when I change the location of the Javascript code to head tag, it's not working.
<html>
<head>
<title>key events</title>
<script>
document.getElementById("submit").addEventListener("click",eve);
function eve(){
var uname = document.getElementById("uname").value;
uname = uname.toUpperCase();
document.getElementById("uname").value=uname;
}
</script>
</head>
<body>
<input type="text" id="uname" length="20" /><br />
<input type="submit" id="submit" value="submit" />
</body>
</html>
Use a document.ready function.
When you put the code before closing the body tag, the DOM has been completely created.
Different case when you put it inside the head tag
Scripts located within the head are executed before the body has been rendered. So the elements you're trying to target don't exist yet.
Try wrapping js referencing element within window.onload event handler where js is within head element; as the #submit element is not loaded into DOM when .addEventListener attached to document.getElementById("submit")
<html>
<head>
<title>key events</title>
<script>
window.onload = function() {
document.getElementById("submit").addEventListener("click", eve);
function eve() {
var uname = document.getElementById("uname").value;
uname = uname.toUpperCase();
document.getElementById("uname").value = uname;
}
}
</script>
</head>
<body>
<input type="text" id="uname" length="20" />
<br />
<input type="submit" id="submit" value="submit" />
</body>
</html>
When in the head, your script executes before the rest of the page is loaded. Make sure you wait for your page to be loaded :
window.onload = function() {
document.getElementById("submit").addEventListener("click",eve);
function eve(){
var uname = document.getElementById("uname").value;
uname = uname.toUpperCase();
document.getElementById("uname").value=uname;
}
}