Javascript Error Null is not an Object - javascript

Im getting a error in the Web Inspector as shown below:
TypeError: 'null' is not an object (evaluating 'myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}')
Here is my Code (HTML):
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<script src="js/script.js" type="text/javascript"></script>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
Here is the JS:
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
Any Idea why I am getting the error?

Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.
document.getElementById() returns null if the element couldn't be found. Property assignment can only occur on objects. null is not an object (contrary to what typeof says).

Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML.
So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/

Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>

I think the error because the elements are undefined ,so you need to add window.onload event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}

I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.
This is what I would do
<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;
function setup() {
myButton = document.getElementById("myButton");
myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName("h2")[0].innerHTML = greeting;
}
</script>
<body onload="setup()">
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
</body>
</html>
have fun!

Related

If statement doesn't work in JavaScript - HTML

I'm pretty new to HTML, and I'm trying to make a simple login system. I'm using Sublime Text 3 and "If" statements in JavaScript don't work. When I type 'if' in script, it goes purple, not JavaScript blue. Am I bad or is Sublime not working at all?
Code:
<html>
<body>
Kullanıcı adı: <input type="text" id="kadi">
<br>
Şifre:<input type="text" id="sifre">
<br>
<button type="button" onclick="fun()">Giriş Yap</button>
<p id="p"></p>
<script type="text/javascript">
function fun(){
var gkadi = document.getElementById().value;
var gsif = document.getElementById().value;
var dkadi = "ali";
var dsif = "aa123"
if(gkadi==dkadi){
if(gsif==dsif){
document.getElementById("p").innerHTML = "Giriş başarılı!";
} else {
document.getElementById("p").innerHTML = "Şifre yanlış";
}
} else {
document.getElementById("p").innerHTML = "Kullanıcı adı yanlış.";
}
}
</script>
</body>
</html>
The syntax coloring can be misleading. It's not your if statement that is having problems. It's that getElementById() expects one argument which should be the id of the element that you are trying to get. With that change, your code works fine.
function fun() {
var gkadi = document.getElementById("kadi").value;
var gsif = document.getElementById("sifre").value;
var dkadi = "ali";
var dsif = "aa123"
if (gkadi == dkadi) {
if (gsif == dsif) {
document.getElementById("p").innerHTML = "Giriş başarılı!";
} else {
document.getElementById("p").innerHTML = "Şifre yanlış";
}
} else {
document.getElementById("p").innerHTML = "Kullanıcı adı yanlış.";
}
}
Kullanıcı adı: <input type="text" id="kadi">
<br> Şifre:
<input type="text" id="sifre">
<br>
<button type="button" onclick="fun()">Giriş Yap</button>
<p id="p"></p>

Javascript " onsubmit " Event Not Working Correctly

I am just practicing js. I am trying to make a very simple validation in form but it came with, as i was expecting, an error.
Here's my code :
var form = document.getElementById('form');
var name = document.getElementById('name');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
if (name.value == "")
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
The problem is that, it doesn't validate it. Every time it returns true on submitting but when i replace the " name.value" with "email.value" the code works. I don't know now what's the problem actually. If someone could help me..
It looks like the input with id name is not created in DOM by the time of JavaScript execution.
You can resolve that by putting the code in the window.onload code block or inside the form.onsubmit
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c) {
var name = document.getElementById('name');
if (name.value == "") {
error.innerHTML = "Error Submiting Form !";
return false;
} else {
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
};
handlingForm();
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
Your variable called name is a problem. It's not working because name is a predefined identifier in some implementations. Though it's not a reserved keyword, it's best practice to avoid using it as a variable name.
Rename it to name_ (or almost anything else) and it will work.
If name.value has no value, it is undefined. So undefined !== "", which is why it will never be true. Just do a null check for name.value. Also, you need to move name inside of that function since the first time it is called, value will always be undefined:
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
var name = document.getElementById('name');
if (!name.value)
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
Try this:
window.onload = handlingForm();
Why your function has c parameter?
This is due to a quirk of how global variables are handled in web pages. Each one is treated as a property of the window object, so when you assign to email, you're actually creating and assigning to window.email, and so on.
However, some properties of the window object already exist and have special meaning to the browser, such as window.location (the current URL) and window.name (used in cross-frame link targets).
To see it in practice, do this in the global scope (outside any function):
var location; // should be undefined, right?
alert(location); // but it's actually window.location
Because of the special meaning of window.name, anything you assign to it (or to global name) will be converted into a string. The element that you try to store becomes a string, and so no longer works as an element.
To fix it, simply move your code into a function, so that the variables are local and no longer have this strange behaviour. You can use your window.onload function for this.

How to Get and Print a String Using HTML

I have a small project that I'm working on (dealing with getting a name and printing it with a string). The problem is that when I click on the button, nothing happens.
Code:
<!DOCTYPE html>
<html>
<head>
<link type = "css" rel="stylesheet" href = "css.css"/>
<script>
var button = document.getElementById('send');
var enter = document.getElementById('enter');
button.onclick function() {
var str = 'Hello ' + enter.value + ' how are you?';
alert(str);
}
</script>
<title>HAL 9000 SIM</title>
</head>
<body>
<p id=p1> What is your name? </p>
<br><br>
<input type = "text" id="enter" name = "entername"><br>
<input type = "button" id="send" value="Enter">
</html>
It's not complete, as you can probably tell, so any other pointers are greatly needed!
It seems you forgot the "=" sign after the button.click.
Check this:
<body>
<p id=p1>What is your name?</p>
<br>
<br>
<input type="text" id="enter" name="entername">
<br>
<input type="button" id="send" value="Enter">
--
var button = document.getElementById('send');
var enter = document.getElementById('enter');
button.onclick =
function () {
if(enter.value.length > 0)
{
var str = 'Hello ' + enter.value + ' how are you?';
alert(str);
}else
{
alert("Please input the required fields!");
}
};
http://jsfiddle.net/pg5k60rz/
First of all, you didnt assign to onclick your function
var enter = document.getElementById('enter');
button.onclick = function() {
var str = 'Hello ' + enter.value + ' how are you?';
alert(str);
}
secondly if you want your code work, but script before closing body tag

Javascript: a variable contains value but Firebug says it is null

When i click on the button, nothing happens. Firebug says that "TypeError: btnNew is null"
My Javascript code is:
function addNewItem(){
alert("Test")
};
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
And the html is:
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>
How come btnNew is null if its value is document.getElementById("btnAdd") ?
function addNewItem(){
alert("Test")
}
window.onload = function() {
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
}
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>
You have to execute your js code after the document is loaded.
In window.onload or $document.ready() if you use jquery.
See window.onload vs $(document).ready() for differences.
you could use body onload event
see the code bellow
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>
<script>
function myFunction() {
function addNewItem(){
alert("Test")
};
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
}
</script>
</body>
</html>

Uncaught ReferenceError: myFunction is not defined

Gives an error. I have placed the code just before </body>. Still getting the error.
<form action="" method="get" id="searchform" >
<input name="q" type="text" id="search" size="32" maxlength="128" class="txt">
<input type="button" id="hit" value="Search" onclick="myFunction();return false" class="btn">
</form>
JS,
<script type="text/javascript">
var nexturl = "";
var lastid = "";
var param;
$(document).ready(function () {
function myFunction() {
param = $('#search').val();
alert("I am an alert box!");
if (param != "") {
$("#status").show();
var u = 'https://graph.facebook.com/search/?callback=&limit=100&q=' + param;
getResults(u);
}
}
$("#more").click(function () {
$("#status").show();
$("#more").hide();
pageTracker._trackPageview('/?q=/more');
var u = nexturl;
getResults(u);
});
});
</script>
You cannot place myFunction after the onclick. When the onclick is seen there is no definition for myFunction.
Place the JavaScript in <head> tag. Also, move the function outside of ready().
Like this:
<script type="text/javascript">
var nexturl ="";
var lastid ="";
var param;
function myFunction() {
param = $('#search').val();
alert("I am an alert box!");
if (param != "") {
$("#status").show();
var u = 'https://graph.facebook.com/search/?callback=&limit=100&q='+param;
getResults(u);
}
}
$(document).ready(function() {
$("#more").click(function () {
$("#status").show();
$("#more").hide();
pageTracker._trackPageview('/?q=/more');
var u = nexturl;
getResults(u);
});
});
</script>
</head>
<body>
...
keep myFunction in script tag directly
i.e
<script>
function myFunction() {
.....
}
</script>
From the jQuery docs:
The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
So your function isn't created until after your onclick is established. Thus it can't find the function. You'll want to move it outside the $(document).ready(function(){}).
You have to move the function outside the $document.ready here then you will have two options: 1st move it to <head> or 2nd move it right before the closing $document.ready bracket. Use this type of declaration for your function myFunction(){alert("inside my function");};

Categories