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

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>

Related

Why aren't the user inputs being put into the empty array?

I'm trying to write a program so that once the user clicks the 'Add!' button, the string that they typed will be added to an initially empty array in an object, and then that updated array will be displayed back on the HTML page. However, when I checked what the value of the items array was when I typed something in, it still appeared to be null. I'm fairly certain that the addItem function is fine, is the problem in the updateList function?
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Homework 5</title>
<!--<link rel="stylesheet" type="text/css" href="index.css">-->
<script src="toDoList.js"></script>
</head>
<body>
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
</body>
</html>
JAVASCRIPT CODE:
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput());
The second argument provided to addEventListener needs to be a function. If you put a function invocation there, that function is executed immediately, with its return value assigned as the handler. But if the return value isn't a function, the event listener doesn't work.
In your case, you just want getInput to be run when the button is clicked - getInput is not a higher-order function, so just pass the function itself, rather than invoking it:
button.addEventListener('click', getInput);
Like this
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
You should not invoke or execute the function in addEventListener. Invoking function causes the function to execute immediately not when the event (click) happens. So remove parenthesis after the function name.
Change button.addEventListener('click', getInput());
To
button.addEventListener('click', getInput);
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
I think, you have to loop through your array. to get the content:
var x = ['apple','banana','orange'];
var output = "";
for (i=0;i<x.length;i++) {
output += x[i];
}
alert(output); //--> outputs applebananaorange
alert(x.items); //--> undefined (whats your case)

how to make an event happen when click a button on HTML by using javascript

I am trying to make HTML print out "Germany" when you click the button. But it is not working correctly. Is there something wrong in my code?
HTML
<input type="button" value="click!" onclick="shuffle();"/>
<div id="output"></div>
Javascript
(function(){
window.onload = function(){
alert("welcome to my trip record");
}
})();
var shuffle = function(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
Remove the ; from your onclick
<input type="button" value="click!" onclick="shuffle()"/>
Try to use addEventListener for make event on button click
document.getElementById("myBtn").addEventListener("click", function(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
});
here is the working jsfiddle:https://jsfiddle.net/jxjpzvvz/
You made two mistakes First mistake <input /> this is nothing. Second most common "function ();", the ";" Is wrong
Your corrected code
(function(){
window.onload = function(){
alert("welcome to my trip record");
}
})();
var shuffle = function(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
<input type="button" value="click!" onclick="shuffle()"/>
<div id="output"></div>
I like to use DOM EventListener
window.onload = function(){
alert("welcome to my trip record");
}
document.getElementById("myBtn").addEventListener("click", function_t);
function function_t(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
<input type="button" value="click!" id = "myBtn" >
<div id="output"></div>
<button id='btn_click' type="button">Click me!</button>
<div id="output"></div>
use button element for buttons, not input type button. we are not in the time of html 4.0 ;)
(function(){
window.onload = function(){
alert("welcome to my trip record");
}
})();
var shuffle = function(event){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
document.getElementById('btn_click').addEventListener('click', shuffle);
i'm fan of no js in the html tags directly, so i add a listener to the element

Disabling html button using JavaScript won't POST

I have this Javascript and HTML code for my button:
function lockoutSubmit(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function(){
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
<button style="margin-right:-160px;" type="submit" name="gen" onclick="lockoutSubmit(this)" class="btn btn-danger btn-block">Generate account!</button>
The code works fine for disabling the button for 3 seconds but the button is no longer posting to "gen".
Change the innerHTML instead of the value and bind the parameters to the settimeout instead of relying on the context.
Also button value might not be what you think it is:
http://www.w3schools.com/tags/att_button_value.asp
<html>
<head>
<script>
function _Unlock(){
var tB = document.getElementById('gen');
tB.removeAttribute('disabled');
tB.innerHTML = 'Generate account!';
localStorage.setItem('Lock', 0);
}
function Unlock(){
var tS = localStorage.getItem('Lock');
if (tS != '1') _Unlock()
else{
setTimeout(function(e, v){
_Unlock()
}, 3000)
}
}
function setToLock(){
localStorage.setItem('Lock', 1);
}
</script>
</head>
<body onload = 'Unlock()'>
<!-- Do you have a form and is it setup correctly? -->
<form action = '' method = 'post' id = 'myForm' onsubmit = 'setToLock()'>
<button id = 'gen' type = 'submit' name = 'gen' disabled = 'disabled'>...processing...</button>
<form>
</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");};

Javascript Error Null is not an Object

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!

Categories