javascript document. getElementById('').value returns 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.
If I directly insert the method document.getElementById in the method setTimeout it works fine
1.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, document.getElementById("numbers").value);
}
</script>
<input id="numbers" type="textbox" />
</body>
</html>
2.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
var numbers = document.getElementById("numbers").value
function myFunction() {
setTimeout(function(){ alert("Hello"); }, numbers);
}
</script>
<input id="numbers" type="textbox" />
</body>
</html>
Why the second one doesn't work? I think that the var numbers returns null, but I don't know why.

The line var numbers = document.getElementById("numbers").value is being executed on the load of your page, numbers does not exist yet.

In the first version you are retrieving the element and its value when the click event fires and calls the attached handler. In that moment the input field has a value which is returned.
In the 2nd version you are retrieving the input element and its value when the input field does not exists in the DOM, thus null is used when the handler is called. Obviously you should go for the former.

Like #gmiley has said, numbers doesn't exist it yet. You should include:
var numbers = document.getElementById("numbers").value
inside of your function.
Also, on a side note...It's probably not best to put your javascript in the middle of the file. I almost didn't see the 'input' after the 'script' tags.

Related

Cannot read property 'addEventListener' of null at dice.js:5

I'm trying to implement a function that will create new divs inside another div based on the number typed by user.
I wanted to do this with addEventListener to the input and ran a test to check if it even works. But it doesnt and I dont know what im doing wrong. Here is my HTML code:
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber">
</form>
and JS part:
var numInput = document.querySelector("input");
numInput.addEventListener("change", function(){
alert("test");
});
How are you including your javascript file in the html document? It may be possible that your JS code is being executed before the html is loaded.
It is hard to answer only with these 2 snippets.
My guess is that you have something like
<html>
<head>
<script>
var numInput = document.querySelector("input");
numInput.addEventListener("change", function(){
alert("test");
});
</script>
</head>
<body>
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber">
</form>
</body>
</html>
In this case, the script will be executed before the dom is loaded which is why the code cannot find the input.
you either have to wait that the dom is ready or move the script block after the definition of the input.

Why doesn't onClick activate function? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I'm trying to write a simple code in JavaScript where selecting a button calls a prompt function, but the prompt never pops.
This is the HTML:
<div id="btnDiv">
<button type="submit" id="btn" onclick="submit"> send info </button>
</div>
And this is the JavaScript code:
document.getElementById("btn").onclick = function(){
prompt("Thank you");
}
What am I doing wrong?
Make sure that the JS code is loaded after the HTML content, you can use onLoad event:
window.onload=function(){
document.getElementById("btn").onclick = function(){
prompt("Thank you");
}
};

Calling a recursive javascript within a form

I have this problem. I am trying to make a button "click it self" using a setTimeout function in javascript. I need this small piece of code to function to be able to simulate a refresh. The problem is, because the button on which I'm calling the refresh is within a form tag, this operation only occurs once, instead of continuously repeating itself. Here is my javascript
<script language="javascript" type="text/javascript">
function ClickMe(){
setInterval('document.getElementById("auto").click()',5000);
alert("Function works");
}
</script>
Here is the element on which I am calling it.
<form>
<input id="auto" type="submit" value="Click" onClick="ClickMe()" />
</form>
If you remove the "<form></form>" tag, the code runs normally by calling itself again and again every 5 seconds. Byt once you add the "<form>" tag, the function is only called once. If someone could help me out, I'll be really grateful. Thanks
For whatever reason you want to do this, just change your submit to a button like so:
<input id="auto" type="button" value="Click" onClick="ClickMe()" />
also, you should note that you're going to keep creating more and more intervals for this each time it's ran.
When you wrap the input with form, the form is submitted, you can avoid that by returning false in the ClickMe function.
function ClickMe(){
setInterval('document.getElementById("auto").click()',5000);
alert("Function works");
return false;
}

HTML/JS Execution Order

I am trying to understand the Execution Order of HTML and JS functions.
Code:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x=document.getElementsByName("check1");
x[0].disabled=true;
x[0].checked=true;
x[0].value="Y";
}
function myFunction1()
{
var x=document.getElementsByName("check1");
alert(x[0].value);
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
<form>
<input type="checkbox" name="check1" unchecked enabled value="N"/>
<input type="button" value="Button" onclick="myFunction1()"/>
</form>
</body>
</html>
Finally the element "check1" value is =Y.
finally checkbox is checked and disabled.
Can anyone explain about this.
I have already gone through this link which is very useful:
Load and execution sequence of a web page?
Still the above example will help bit more .Thanks
first you change the name of functions.. it must be different. then the execuation order is
first onbody load function is called then input button function called.
you can even check it by alert that.
The "myFunction()" method called in on load event so that it executed immediately after a page is loaded. and the function "myFunction1()" called on button click event .And you are initializing check box value with "N" value thats why it displaying n after every page load function
If I understood your question you mean why your checkbox value is 'Y' despite you disabled the checkbox.
disabling checkbox only make it inactive as far as User Interface is concerned but through script you can still change the value.

Reading inputs and printing variables - JavaScript and HTML 4.01

I've just been testing some code, and I can't get this to work:
<HTML>
<head>
<title> Page 1 </title>
<script>
function myFunction()
{
var x=document.getElementById("myEmail")
document.write(x)
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</HTML>
All I'm trying to is have the user type something into a text, being read by the parser, putting it into a variable, then printing the variable on screen. It would help me a lot with other projects I've got on if I knew this. Can anyone help?
NOTE: I don't want to use HTML5 because it removes some of the tags that I like, so could we use HTML 4.01 or something?
Step 1 is to use HTML 5, indent your code, and use semicolons.
<!DOCTYPE html>
<html>
<head>
<title> Page 1 </title>
<script>
function myFunction() {
var x = document.getElementById("myEmail");
document.write(x);
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</html>
Step 2 is to look at what’s being written, see that it’s null, intuit when document.getElementById would return null, and realize that there is no element with an id of myEmail in your document. It just has a name. Drop the form while you’re at it.
<body>
<p>Input your email </p>
<input id="myEmail" type="text">
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
The next step is to try that again and realize that x is an element, not a string, and you want to get its value.
function myFunction() {
var x = document.getElementById("myEmail");
document.write(x.value);
}
The “good future practice” steps are, in no particular order:
Put your script at the bottom and stop using inline event listeners
Put your script in an external file
Use a <label>
If you’re not going to do something more useful than write the e-mail back, consider also using document.body.appendChild(document.createTextNode(…)), which will not obliterate the rest of the document. The DOM is really great.
Add an id to the input
<input name="myEmail" type="text" id="myEmail">
then write the value
document.write(x.value)
document.getElementById returns the DOM element. Printing the DOM element is not meaningful and its output may vary by browser.
What you want is to print the input value of the input field, so check the value property:
function myFunction()
{
var x=document.getElementById("myEmail").value
document.write(x)
}
Secondly, your HTML code does not have an ID attribute on the element, so the getElementById lookup will fail. Add an ID:
<input name="myEmail" type="text" id="myEmail">
Regarding your note about HTML 4 vs. HTML 5.
NOTE: I don't want to use HTML5 because it removes some of the tags that I like, so could we use HTML 4.01 or something?
That comment is interesting. Without knowing specifically which tags you are referring to, I cannot say why they are removed, but I imagine there is likely an equivalent. HTML 5 does not remove any capabilities of HTML that I am aware of.
That is like saying you won't drive a car with an automatic transmission because it doesn't have a clutch.
All you have to do is add an id attribute having the same value as the value of your name attribute of input type="text" and modify your script to store value instead of the element itself.
<html>
<head>
<title> Page 1 </title>
<script>
function myFunction()
{
var x=document.getElementById("myEmail").value;
document.write(x);
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" id="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</html>

Categories

Resources