document.getElementById('id') is null javascript error - javascript

For some reason I get an document.getElementById('id') is null JS error on line 7 with the following markup and script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
document.getElementById('calculate').onclick = function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
};
document.getElementById('erase').onlick = this.form.reset();
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button">
<input id="erase" value="Clear" type="button">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
What's the real problem here?

It is indeed null. Your element doesn't exist on the page yet.
Either:
Move your <script> block below your code
Add a window.onload event.

Alternatively: window.onload = function(){} works as well

If you don't feel like including jQuery, then document.ready = function () {} will work fine too.

At the point which the javascript is actually run, there is no element with an id of 'calculate'. You need to make sure your javascript runs after your required elements have been created. My advice would be to use a common javascript framework like jquery. You would then just attach your script to run on dom ready:
$(document).ready(function() {
// Handler for .ready() called.
});

You can fix it by moving the script to the end of the body, or try to use window.onload, or window.addEventListenner
Check the http://v3.thewatchmakerproject.com/journal/168/javascript-the-dom-addeventlistener-and-attachevent
and http://javascript.about.com/library/blonload.htm

using windows.onload
add link file script or script below "body end tag"

Related

Why the button object can not use the onclick() function?

I am trying to use javascript to create a web calculator. I hope that users can calculate the result when they click the different buttons. However, there is an error in line16(Uncaught TypeError: Cannot read property 'onclick' of null). I hope someone could help me. These are my codes:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var btnadd,btnsub,btnmul,btndiv;
btnadd = document.getElementById('btnadd');
btnsub = document.getElementById('btnsub');
btnmul = document.getElementById('btnmul');
btndiv = document.getElementById('btndiv');
btnadd.onclick() = function(){
cal(add());
}
function cal(func){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
parseFloat(num1);
parseFloat(num2);
var result;
result = func(num1,num2);
document.getElementById('result').value = result;
}
function add(num1,num2){
return (num1+num2);
}
function sub(num1,num2){
return (num1-num2);
}
function mul(num1,num2){
return (num1*num2);
}
function div(num1,num2){
return (num1/num2);
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="num1" /><br>
num2:<input type="text" id="num2" /><br>
<input type="button" id="btnadd" value="add" />
<input type="button" id="btnsub" value="sub" />
<input type="button" id="btnmul" value="mul" />
<input type="button" id="btndiv" value="div" /><br>
result:<input type="text" id="result"/>
</form>
</body>
</html>
You need to either add the defer attribute to your script or put it at the end of the body.
Putting JS code in the head means that it will be run before the page is fully parsed. That means that there is no element with the id of btnadd just yet. If you add the defer attribute, then it will wait for the page to be parsed before running the script. Putting at the end of the body has the same effect.
In terms of your code itself, you need to set the onclick property. You cannot assign a function like that. Also, do val2 = parseFloat(val2) rather than parseFloat(val2). (similarly for val1) because here you need to reassign the value
Because you didn't define the onclick correctly
Instead of
btnadd.onclick() = function(){
cal(add());
}
try
btnadd.onclick = function(){
cal(add);
}
Check this codepen : https://codepen.io/zecka/pen/NWrejxO
Note that there are other errors in your code that will prevent you from making it work as you want.

Why is my button not activating my validation function

I have an html page that access an external javascript file to validate the users input. My button doesnt seem to be doing anything and I dont understand why.
<html lang = "en">
<head>
<title>random</title>
</head>
<body>
<form>
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="15">
<input type="button" value="validate" onclick="validationFunction()">
<p id = "validationResults"></p>
</body>
</html>
//My external JS file that is supposed to validate the pattern WEB.110#4101_sp-2017
function validationFunction(input) {
var myRegularExpression = /([a-z]{3})(\W\d{3})(\W\d{4})(\W[a-z]{2})(\W\d{4})/gi;
return (myRegularExpression.test(input));
}
if (validationFunction(userInput)){
text = "valid";
} else {
text = "invalid";
}
document.getElementById("validationResults").innerHTML = text;
The below code works for what you want to achieve. Issues I noticed with your code:
Your form element had no closing tag
Rather than adding an onclick to a button within a form, you are better submitting the whole form, and grabbing the event object from an onsubmit event
You need to preventDefault on the event which stops the page refreshing
Your maxLength was set to 15 but your target expression is 20 characters
Your RegEx works, but could be cleaner
<!DOCTYPE html>
<html>
<head>
<title>random</title>
<script src="./script.js" defer></script>
</head>
<body>
<form id="form">
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="20"/>
<input type="submit"></input>
</form>
<p id="validationResults"></p>
</body>
</html>
const form = document.getElementById("form");
const paragraph = document.getElementById("validationResults");
form.addEventListener('submit', validationFunction);
function validationFunction(event) {
event.preventDefault();
const userInput = event.target.querySelector("#userInput").value;
const regEx = /([a-z]{3}(.\d{3})(#\d{4})(_[a-z]{2})(-\d{4}))/gi;
const isValid = regEx.test(userInput);
if (isValid) {
paragraph.innerHTML = "Valid";
} else {
paragraph.innerHTML = "Invalid";
}
};

combining data elements from two html forms is not working properly

I am trying to combine data from two HTML forms and then post it as a single form which is working fine except that some elements are not being copied from one form to the other. I have defined the following javascript function to combine form elements:
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
Actual files
This is the first form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var childWindow = null;
function child_open() {
childWindow = window.open('new.html', "_blank",
"resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if (childWindow && !childWindow.closed)
childWindow.focus();
}
</script>
</head>
<body onclick="parent_disable();">
<input type="button" value="Create Jira Ticket" onclick="child_open()" />
<form name="auth_form" id="Create" method="post">
<input name="bug_status" value="NEW" type="hidden">
<input name="rep_platform" value="All" type="hidden">
<input name="component" value="AFAS" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
<input type="hidden" name="comment" value="hello hi"><br>
</form>
</body>
</html>
and this is second form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var count = 0;
function submit_and_close() {
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
alert(form.innerHTML);
form.submit();
// close the window after form submission is complete.
var docLoaded = setInterval(function() {
if (document.readyState !== "complete") {
return;
}
clearInterval(docLoaded);
//window.close();
}, 30);
}
</script>
</head>
<body>
<header>
<div id="dialog" title="JIRA Dialog">
<h1>JIRA Credentials</h1>
</div>
</header>
<div>
<form name="auth_form" id="auth_form" method="post">
<label> User Name: </label> <input type="text" name="username"><br>
<label> Password: </label> <input type="password" name="password"><br>
<input type="button" value="Log In" onclick="submit_and_close()">
</form>
</div>
</body>
</html>
For example I am not able to see the following elements being copied over from 'Create' form to 'auth_form' in second html page.
<input name="rep_platform" value="All" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
Even after spending sometime debugging, I am not able to figure out why some elements are being succesfully copied while others not.
.elements returns a live collection of elements. When you append an element from the collection, it gets removed from the collection, so your index i into the collection get out of sync, and therefore every other element gets skipped.
Instead, just append the first element from the collection until the collection is empty. (Just detach the submit button element when it is encountered). Alternatively, loop through the collection from last to first rather than first to last.
(querySelectorAll() works because it returns a static collection, rather than a live one.)
Try changing your second form from ...
var issuedata = window.opener.document.getElementById('Create').elements;
to
var issuedata = window.opener.document.querySelectorAll('input[name]');
... and replace all innerHTML with outerHTML

Second exists condition does not work

I'm having a question about javascript where I have two conditions to check if the input fields exists. But it only shows me that "opleiding exists" and not that "opleiding exists" and "domein exists".
please tell me what's wrong with my code.
Thanks very much !
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
if(document.getElementById("opleiding")){
document.write("opleiding exists");
}
if (document.getElementById("domein")){
document.write("domein exists");
}
}
</script>
</head>
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
</html>
document.write will override the existing content in the page. That's the reason why you're seeing only on message.
You must use document.body.appendChild instead to show both error messages.
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
var textElement;
if(document.getElementById("opleiding")){
textElement = document.createElement("p");
textElement.textContent = "opleiding exists";
document.querySelector("#results").appendChild(textElement);
}
if (document.getElementById("domein")){
textElement = document.createElement("p");
textElement.textContent = "domein exists";
document.querySelector("#results").appendChild(textElement);
}
}
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="results"></div>
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
You should avoid using document.write, since that it's a deprecated method. When you use it the first time, it will write down what you want, but remove all the content of the page, as per its definition.
To do what you want you should "write" using either document.body.appendChild to append some element (like a <div>) containing text, or add some text to the document.body.innerHTML, here's an example:
function submit() {
var opleiding_div = document.createElement('div'),
domein_div = document.createElement('div');
opleiding_div.textContent = "opleiding exists";
domein_div.textContent = "domein exists";
if(document.getElementById("opleiding")){
document.body.appendChild(opleiding_div);
}
if (document.getElementById("domein")){
document.body.appendChild(domein_div);
}
}

HTML-form submit button not running the OnSubmit script associated with it

I'm making a chrome extension, and so far I'm just testing some things. The HTML for the extension is this:
<!doctype html>
<html>
<head>
<title>Title</title>
<script src="processform.js"></script>
</head>
<body>
<form name="myform" onSubmit="ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</form>
</body>
</html>
The processform.js file is this:
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
When I press the submit button the alert doesn't appear.
You cannot use inline code in a Chrome extension due to its Content Security Policy, and setting onsubmit in the element counts as inline.
A jQuery-based solution (you will need to include jQuery with the extension and add it to the page, but there's no harm in that):
// processform.js
$(document).ready(function(){
// Bind from JS, not inline
$("form").submit(ExampleJS);
});
A pure JavaScript solution would be:
// processform.js
document.addEventListener('DOMContentLoaded', function(){
// Bind from JS, not inline
document.forms["myform"].addEventListener('submit', ExampleJS);
});
Please put the following code -
$(document).ready(function(){
$("form").submit(ExampleIS);});
This should work.

Categories

Resources