This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 months ago.
So I've just started learning javascript and wanted to make a simple input form and a response form on my webbpage. The problem I had is that if I used a simple submit button then the page would refresh and clear both textfields before I could read the response in the response textfield. So I tried making a button that does nothing and then calling it through javascript onClick but it doesn't seem to work.
console.log("simplejava loaded correctly");
console.log(document.getElementById("button1"));
console.log(document.getElementById("fname"));
document.getElementById("button1").onclick = myFunction();
function myFunction() {
let name = document.getElementById("fname").value;
document.getElementById("response").value = "Hi " + name;
if(name == "John")
{
alert("Hello "+name)
}
}
<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="simplejava.js"></script>
<title>Document</title>
</head>
<body>
<h1>Simple Forms</h1>
<form>
<input type="text" id="fname">
<button type="button" id="button1">Send</button>
<br>
<input type="text" id="response">
</form>
</body>
</html>
You can just add the onclick event to the button at the html, works fine.
console.log("simplejava loaded correctly");
console.log(document.getElementById("button1"));
console.log(document.getElementById("fname"));
function myFunction() {
console.log("Button working")
let name = document.getElementById("fname").value;
document.getElementById("response").value = "Hi " + name;
if(name == "John")
{
alert("Hello "+name)
}
}
<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="simplejava.js"></script>
<title>Document</title>
</head>
<body>
<h1>Simple Forms</h1>
<form>
<input type="text" id="fname">
<button type="button" id="button1" onclick="myFunction()">Send</button>
<br>
<input type="text" id="response">
</form>
</body>
</html>
Use addEventListener instead.
console.log("simplejava loaded correctly");
console.log(document.getElementById("button1"));
console.log(document.getElementById("fname"));
// document.getElementById("button1").onclick = myFunction();
document.getElementById("button1").addEventListener('click', () => myFunction());
function myFunction() {
let name = document.getElementById("fname").value;
document.getElementById("response").value = "Hi " + name;
if (name == "John") {
alert("Hello " + name)
}
}
<h1>Simple Forms</h1>
<form>
<input type="text" id="fname">
<button type="button" id="button1">Send</button>
<br>
<input type="text" id="response">
</form>
Related
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.
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>
I need to create a simple form with a button that calculates a number into a factorial. The calculation has to be done from the button and the answer needs to pop up in an alert box.
Embarisngly I've tried to figure this out for hours but I can not get the button to work and the workaround is to hit enter but then the answer does not display.
<script>
var n = document.getElementById('x1').value;
function fac(N) {
if (N > 1) return n * fac(N - 1);
else return N;
}
alert("Answer is "+ fac(N));
</script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>factorial</title>
</head>
<body>
<h2>Generate Your Factorial!</h2>
<form>
<label>Enter Number: </label><br>
<input type="text" id="x1"><br>
<input type="button" value= "Generate" onclick="fac(N)">
</form>
</body>
</html>
I think there is a confusion between the value passed and the one used in the function, try something like this
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>factorial</title>
</head>
<body>
<h2>Generate Your Factorial!</h2>
<form>
<label>Enter Number: </label><br>
<input type="text" id="x1"><br>
<input type="button" value= "Generate" onclick="getFac()">
</form>
<script>
function fac(N) {
if (N > 1) {
return N * fac(N - 1)
}
else{
return N
}
}
function getFac(){
var n = document.getElementById('x1').value;
alert("Answer is "+ fac(n));
}
</script>
</body>
</html>
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>
I am attempting to check if an input contains anything in it upon the press of a button. It only seems to be checking the value upon the first load of the website. It is not detecting any values typed into the input even if the button is pressed again and again. I have tested this by setting the input value to something at default, which gave me a success. I am stumped as to why this is happening.
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>test</title>
</head>
<body>
<label>Goals:</label>
<input type="text" class="input-box" id="goals" />
<input
type="button"
name="submit"
value="Submit"
class="button"
id="submit"
/>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"
></script>
<script src="./app.js"></script>
</html>
JavaScript:
// Gather Inputs
let goals = document.getElementById("goals").value;
console.log("goals");
$("#submit").click(function() {
// Check Goals Input
if (goals === "") {
console.log("fail");
} else {
window.print();
}
});
You need to gather the inputs within the click() function.
$("#submit").click(function() {
// Gather Inputs
let goals = document.getElementById("goals").value;
console.log("goals");
// Check Goals Input
if (goals === "") {
console.log("fail");
} else {
window.print();
}
});