Form button 'Cannot set property 'onclick' of null' [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I can't determine what is 'null'. I think it may be the form button, because of the form and button ids aren't the same... The console is saying the problem is on the 'button1.onclick = createParagraph;' line. Please help.
Below is my javascript
//global variables for user input
var noun1;
var noun2;
var adjective1;
var adjective2;
var verb1;
var verb2;
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")
//to retrieve values from user input, and write to global variables
function handleSubmit(form) {
noun1 = form.querySelector('input[name=noun1]').value;
noun2 = form.querySelector('input[name=noun2]').value;
adjective1 = form.querySelector('input[name=adjective1]').value;
adjective2 = form.querySelector('input[name=adjective2]').value;
verb1 = form.querySelector('input[name=verb1]').value;
verb2 = form.querySelector('input[name=verb2]').value;
return false;
}
//to write paragraph to the DOM
function createParagraph () {
var element = document.createElement("p");
var content = document.createTextNode("paragraph1");
var location = document.getElementById("placeholder");
element.appendChild(content);
document.body.insertBefore(element,location);
}
//run it all!
button1.onclick = createParagraph;
Below is HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="stylesheets/madlib.css">
<script src="randomMad.js"></script>
<title>Mad Libs!</title>
</head>
<header>
</header>
<body>
<form onsubmit="return handleSubmit(this)" id="form1">
<h1>Choose your words!</h1>
<fieldset>
<label>First Noun: <input type="text" name="noun1" ></label><br>
<label>Second Noun: <input type="text" name="noun2"></label><br>
<label>First Adjective: <input type="text" name="adjective1"></label><br>
<label>Second Adjective: <input type="text" name="adjective2"></label><br>
<label>First Verb: <input type="text" name="verb1"></label><br>
<label>Second Verb: <input type="text" name="verb2"></label><br>
</fieldset>
<button type="submit" id="pushMe">Create Mad Lib</button>
</form>
<div id="placeholder">
</div>
</body>

You are missing ; in some of your lines..
See
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")
Kindly add a ; at the end of that two lines.
UPDATE
The error may be causing because you are trying to access the element before the DOM has finished loading. Thus to solve that problem, you can just move
<script src="randomMad.js"></script>
to the end of <body> .

Related

I'm trying to make a form based calculatorfor a business equation

I'm trying to create a form based calculator for a business equation which works out break-even return on ad spend.
The fucntion works, I've testred it through the console on Chrome. But this is ony when I set the variables to numbers, I'm struggling to use the data from the form to work it out.
I don't know if using a form is right for this. The part I can't figure out is linking the HTML form data to the JS variables.
<!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="stylesheet" href="style.css">
<title></title>
</head>
<body>
<form id="main">
<label for="rprice">Retail Price: </label>
<input type="number" id="rprice"><br><br>
<label for="cogoods">Cost of Goods: </label>
<input type="number" id="cogoods"><br><br>
</form>
</body>
</html>
let retailPrice = document.getElementById("rprice")
let costOfGoods = document.getElementById("cogoods")
let difference = retailPrice - costOfGoods
function calculate () {
return (retailPrice / difference)
};
Take in consideration:
to get the value of any input use attribute .value
function calculate (){
let difference = retailPrice.value - costOfGoods.value
return retailPrice.value / difference
};
Add submit input to fire the function calculate()
<input type="submit" value="calculate">
to get the returned value from a function you have to call it.
let form = document.getElementById("main");
form.addEventListener("submit",function(event){
event.preventDefault();
console.log(calculate());
});
Note: event.preventDefault() prevent the form from reloading.
let retailPrice = document.getElementById("rprice");
let costOfGoods = document.getElementById("cogoods");
let form = document.getElementById("main");
form.addEventListener("submit",function(event){
event.preventDefault();
console.log(calculate());
document.getElementById("display").innerHTML = calculate();
});
function calculate (){
let difference = retailPrice.value - costOfGoods.value
return retailPrice.value / difference
};
<form id="main">
<label for="rprice">Retail Price: </label>
<input type="number" id="rprice" ><br><br>
<label for="cogoods">Cost of Goods: </label>
<input type="number" id="cogoods" ><br><br>
<input type="submit" value="calculate">
</form>
<div id="display"></div>

How do I trigger a JavaScript function when a button is pressed in HTML code

I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>

My javascript won't run, Is the file not linked correctly? [duplicate]

This question already has answers here:
Why JS function name conflicts with element ID?
(3 answers)
Closed 4 years ago.
I'm very new to this and I can't figure out whats wrong with my school project. I think maybe my javascript file isn't linked correctly, or maybe the code is just broken?
// }
// Commented out above "}" - Edits must be at least 6 characters
function repost() {
var epost = document.getElementById('epost');
var repost = document.getElementById('repost');
if (epost.value != repost.value) {
repost.setCustomValidity('Epost adresserna måste matcha.');
} else {
// input is valid -- reset the error message
repost.setCustomValidity('');
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Skapa konto</title>
<link href="Stilmall.css" rel="stylesheet" type="text/css">
<script>var __adobewebfontsappname__="dreamweaver"</script>
<script src="http://use.edgefonts.net/abel:n4:default.js" type="text/javascript"></script>
<script src="reg.js" type="text/javascript"></script>
</head>
<body>
<div class="form1">
<form name="form2" id="form3" method="post" onsubmit="return validateForm();" action="tack.html">
<p class="form_text">
<input type="text" id="epost" placeholder="E-post" required>
<input type="text" id="repost" placeholder="Repetera E-post" required oninput="repost(this)">
</p>
<p class="form_text">
<input type="submit" id="sumbit" value="Registrera">
</p>
</form>
</div>
</body>
</html>
Hmm, this is a bit tricky but your id and function name both are "repost", in this situation you will get an error saying repost is not a function and you have to change the name of function or id. this has been discussed here : Why JS function name conflicts with element ID?
Also don't forget to fix the typo in your if condition.

JS input value assigning to variable - undefined

I'm really fresh to JS
Need some help because I don't understand a thing.
If I try to assign the whole line to variable, I can use this variable later, but the outcome of that is blank or undefined, when I'm trying to log this to console, or either alert that
using opera/chrome it's still the same, am I doing something wrong?
HTML
<input type="text" id="name" placeholder="username">
JS
not working
var name = document.getElementById('name').value;
console.log(name);
can't do that either
var name = document.getElementById('name');
console.log(name.value);
innerHTML not working
I can do only that
console.log(document.getElementById('name').value);
UPDATING THE CODE TO FULL EXAMPLE
So I've changed the variable name to nameInp but it isn't working
<!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>
<link rel="stylesheet" href="main.css">
</head>
<body>
<input type="text" id="name" placeholder="podaj imię">
<input type="text" id="name2">
<input type="text" id="name3">
<!--
<input type="password" id="password" placeholder="podaj hasło">
<input type="password" id="confPassword" placeholder="powtórz hasło">
-->
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
<!--
<p id="para"></p>
-->
<div class="center"></div>
<div class="center2"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="main.js"></script>
</body>
</html>
var nameInp = document.getElementById('name').value;
var btn = document.getElementById('submit');
function check(){
console.log(nameInp);
}
Here's your code reduced to the relevant parts:
var nameInp = document.getElementById('name').value;
function check() {
console.log(nameInp);
}
<input type="text" id="name" placeholder="podaj imię">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
The problem is that var nameInp = document.getElementById('name').value; is executed right when main.js is loaded (which happens as part of the whole page loading). At that point the input field has no value yet, so this is equivalent to var nameInp = "";.
Later, when the user clicks on the submit button, the check function runs, but nothing has changed the nameInp variable. It still contains "", so you get no output.
Here's a clearer demonstration of the problem, where the initial value is not "" but "initial value":
var nameInp = document.getElementById('name').value;
function check() {
console.log(nameInp);
}
<input type="text" id="name" placeholder="podaj imię" value="initial value">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
Every time you click on wyślij, initial value is printed because that's what nameInp was initially set to.
Fix:
var nameInp = document.getElementById('name');
function check() {
console.log(nameInp.value);
}
<input type="text" id="name" placeholder="podaj imię">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
Here we only retrieve the .value of the input field at the time check() is run, i.e. when the button is clicked.
You can't see anything in the console because you're outputting the value of the input when the script is called so essentially on page load. At this point the input box hasn't been filled yet. That's the console.log doesn't show anything.
You can, for example, run your function every time the user types inside the input box. For this you will need an event listener:
Select the element you desire to 'watch' and call the addEventListener() method on it. It takes the event type and a callback function as parameters.
Lastly, in the callback function, we get the value of the input box by accessing the target of the event: e.target. e being the event object and e.target the property target of the event.
The code below will call a console.log() every time the user types in the input box:
document.querySelector('#username').addEventListener('keydown', function (e) {
console.log(e.target.value);
});
<input type="text" id="username" placeholder="username">
I have made a script for all three cases, use it according to your need.
<html>
<head>
<script>
function Consolify() {
var firstMethod = document.getElementById('name').value;
console.log('firstMethod = ', firstMethod);
var secondMethod = document.getElementById('name');
console.log('secondMethod = ', secondMethod.value);
console.log('thirdMethod = ', document.getElementById('name').value);
}
</script>
</head>
<body>
<input type="text" id="name" placeholder="username">
<button onclick="Consolify()">Consolify</button>
</body>
</html>

JavaScript & DOM Logic Appears Correct but Won't Run Right

All I want to do is disable the button if there's no content in ftemp. If there is, I want the button to enable and check if it is numeric. Then I can send the ftemp to the next page. My html :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function content()
{
var ftemp = document.getElementById("ftemp");
if (ftemp.value=="")
{
var convert = document.getElementById("convert").disabled=true;
document.getElementById("error").innerHTML = "";
}
else
{
isNumeric()
}
}
function isNumeric()
{
var ftemp = document.getElementById("ftemp");
if (isNaN(ftemp))
{
var convert = document.getElementById("convert").disabled=true;
document.getElementById("error").innerHTML = "Enter only numbers";
}
else
{
var convert = document.getElementById("convert").disabled=false;
document.getElementById("error").innerHTML = "";
}
}
</script>
</head>
<body onload="content()">
<form method="get" action="celsius">
<p>
<label>
Enter a temperature in Fahrenheit:
</label>
</p>
<p>
<input required id="ftemp" title="Enter only numbers!" size="3"
maxlength="3" onkeyup="content()"/>
<button id="convert" name="convert">Convert to Celsius</button>
</p>
<p id="error" name="error">
</p>
</form>
</body>
</html>
Inside isNumeric():
You are checking: isNaN(ftemp) where ftemp is a DOM element so it cannot be a number. Change to isNaN(parseInt(ftemp.value, 10)).
You have error here:
if (isNaN(ftemp))
Change it to:
if (isNaN(ftemp.value))
The ftemp is a DOM Object. You need to pass the value here.
Fiddle: http://jsbin.com/ocibuc/2

Categories