why is "undefined" showing up on top of my text
function myname() {
document.write('Im john doe ');
}
function myage() {
myname();
document.write('Im 47 years old');
}
document.querySelector('.test').innerHTML=myage();
JSBin here's the full code
function myage(){
myname();
document.write('Im 47 years old')
}
document.querySelector('.test').innerHTML=myage()
In this when You are calling myage() it is not returning anything. So innerHtml for the Selected Target gets nothing.
This is the reason why it's showing Undefined.
When the browser processes a HTML-document and comes across a tag, it needs to execute before continuing building the DOM. As you are trying to access document.querySelector('.test') which is not available at that moment, it has given an undefined. Check out the below code where, the script gets executed with out undefined after the dom loads.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="test"></div>
</body>
<script>
function myname(){
document.write('Im john doe ')
}
function myage(){
myname();
document.write('Im 47 years old')
}
document.addEventListener("DOMContentLoaded", () => {
document.querySelector('.test').innerHTML=myage()
});
</script>
</html>
Related
PLeaseHelp. it wont show the Value, even for form authentication, to get username & password values,I was trying the same methods.
<!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">
<title>Document</title>
</head>
<body>
<h1 id="result">Selected movie is </h1>
<select id="movie" onchange="showmovie()">
<option value="Spiderman">Spiderman</option>
<option value="Spiderman2">Spiderman2</option>
<option value="Spiderman3">Spiderman3</option>
</select>
</body>
</html>
<script>
var movie = document.getElementById("movie").value
function showmovie(){
alert("Changed")
document.getElementById("result").innerHTML="Movie chosen is"+movie
}
</script>
Try with this function showmovie
<script>
function showmovie() {
//Selected option
var selectedMovie = document.getElementById("movie").value;
document.getElementById("result").innerHTML = "Movie chosen is " + selectedMovie;
}
</script>
The issue here is because of the line var movie = document.getElementById("movie").value being executed just one time at the beginning (you could verify that adding console.log(movie); just after the movie variable declaration)
(movie stores then the value 'Spierdaman') and it never executes again with the calls for showmovie() function, so you could just move the movie declaration line above inside the function so it executes each time the action occurs and then having the good values.
Other details : To have a compliant code i suggest moving the script bloc to part just before and dont forget to add semicolons ';' at the end of each line ! + Better approach would be to use an eventListener as suggested by #T.J. Crowder in comments section above
I created an HTML file that has two script
it looks like this
<!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>
</head>
<body>
<script src='src/moduleOne.js'></script>
<script src='src/moduleTwo.js'></script>
</body>
</html>
and the first module of javascript has simple code
(function() {
let hello = 'frank';
})();
and the second one has function inside it
(function() {
function problemIsNotOccur() {
return name === undefined;
}
console.log(problemIsNotOccur());
})();
What should happen is the name should return Error name is undefind or return undefined value
But
name return '' empty string (I don't why that happen)
Your question is not clear in your case name is not defined because is not declared
(function() {
let name; ///name now is undefined
function problemIsNotOccur() {
return name === undefined; /// return true
}
console.log(problemIsNotOccur());
})();
I have just copied your code but instead of using 2 separate files, I put both functions inline and the result is "false" which is what is to be expected. The functions don't make much sense though. The first one only assigns a value to a variable and the other one returns "false" every time because you didn't define "name".
For reference, here is how I tested it:
<!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>
</head>
<body>
<script>
(function() {
let hello = 'frank';
})();
(function() {
function problemIsNotOccur() {
return name === undefined;
}
console.log(problemIsNotOccur());
})();
</script
</body>
</html>
I am trying to console.log in chrome. just basic stuff.this is my html file:
<!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>
</head>
<body>
<h1>hello</h1>
<button onClick="clickme()">click</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
now my js file include
var name="abc";
console.log("hello " + name);
clickme=()=>{
document.body.style.backgroundColor="red";
alert(name);
console.log("hello " + name);
}
The alerts work. The background image gets change on button click but the console.log is not working. It works using node js and when used in edge browser.
Is there something missing.
Make sure you have Info checked in your Default-levels dropdown settings:
console.log() always returns undefined (correct me if I am wrong), but prints the value passed to it in the console.
https://codesandbox.io/s/p9zjw8lxrm
Here I have an alert and console.log. You can see alert is running, but console.log does not get to run until you close the alert.
var name = "abc";
console.log("hello " + name);
document.getElementById("btn").onclick = function() {
clickme();
};
const clickme = () => {
document.body.style.backgroundColor = "red";
alert(name);
console.log("hello " + name);
};
When you first run the problem, you should see an alert, then after would be the console.log
When you load up the page,
First you get hello abc
Then Alert box, you click yes
Then hello abc
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to figure out why the first code works whereas the second doesn't. I'm a tad green on jQuery and Javascript as a whole, but was under the impression that this "$('#location').html(...)" part populated the element with 'location' id. That way if I created a variable to which the results of the request are assigned, it'd do the same job if I had "$('#location').html(variable)". What gives?
Here are the two codes:
First Code(This works)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Current Position</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body >
<div>Location: <span id="location"></span></div>
<script>
$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
$('#location').html(location.city + ", " + location.state + " (" + location.country_name + ")");
});
</script>
</body>
</html>
Second Code(This one doesn't)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Current Position</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body >
<div>Location: <span id="location"></span></div>
<script>
var currentLocation = $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
location.city + ", " + location.state + " (" + location.country_name + ")";
});
$('#location').html(currentLocation);
</script>
</body>
</html>
$.getJson returns a kind of promise, not the value of the request itself. So assigning it's result to a variable won't give you the wanted results. This is the way most asynchronous stuff works. You won't ever be able to assign the result of an asynchronous call that way because the code hasn't successfully ran yet.
The first code it's the correct way to go. Think about it this way:
// Do some *asynchrounous* request
const promise = $.getJson(...arguments...)
// Create a handler funcion or "callback"
const handler = function(value) { console.log(value) }
// Tell the promise to call this function when it get's resolved
promise.done(handler);
Promises have some serious advantages like composability: multiple handlers can be attached.
$.getJson(...)
.done(doStuffA)
.done(doStuffB)
.catch(handleError)
I am working on the base for a simple Russian roulette simulator. Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RR</title>
</head>
<body>
<button onclick=load()>Load</button>
<button onclick=fire()>trigger</button>
<script>
var slot=0;
var load=function(){
slot=Math.Floor(Math.random()*6+1);
};
var fire=function(){
slot=slot-1;
if(slot===0){
confirm("BANG!!");
}else{
if(slot<0){
confirm("There is no bullet in this gun.");
}
}
};
</script>
</body>
</html>
When I click load I get the error in the title. I know Math.Floor is a function because I've used it before and I looked it up. Did I mess something up in the code? Thanks.
Change...
slot=Math.Floor(Math.random()*6+1);
to...
slot=Math.floor(Math.random()*6+1);
As Roland and Sterling pointed out, the floor function starts with a lower case f letter.