I am learning JS as part of my studies and at the moment I am trying some examples from W3Schools and am stuck on JS Functions page. The link of the page is:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_function_return
If I use the example code them the code runs perfectly just as below code:
<html>
<head>
</head>
<body>
<p id="demo"> </p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(3, 4);
</script>
</body>
</html>
But if I take the script portion of the above code inside Head tags just like below code then the function does not execute at all and I do not get any value:
<html>
<head>
<script>
function myFunction(a, b) {
return a * b;
document.getElementById("demo").innerHTML = myFunction(3, 4);
}
</script>
</head>
<body>
<p id="demo"> </p>
<button type="button" onclick="myFunction()">Click me</button>
</body>
</html>
Can someone point me where I am doing wrong and how to fix this issue.
Cheers,
Your code has a couple issues. Here's how to fix it:
First off, you functions return a value at the end of the function, after processing parameters. Having a return at the beginning is bad.
Second, you've got to call the function with arguments from the onclick HTML attribute. Right now, there's nothing in the function call myFunction(). It should look like myFunction(3, 4).
Lastly, what was the point of calling myFunction() within the function declaration? That doesn't make sense.
I've adjusted your code with comments to help you make sense of it. This should be helpful.
<html>
<head>
<script>
function myFunction(a, b) {
// Return is usually the last thing you do in a function.
// Also, don't call a function from within the function.
// Instead, put what you had in return in the demo element's innerHTML.
return document.getElementById("demo").innerHTML = a * b; // a * b,
// not 3 * 4.
}
</script>
</head>
<body>
<p id="demo"> </p>
<!-- Also, there were no arguments here. You need to specify arguments in
the onclick event -->
<button type="button" onclick="myFunction(3, 4)">Click me</button>
</body>
</html>
I hope this is helpful!
When you are calling myFunction in the click handler you are not passing any parameters to it, also the first statement in it is a return statement which means the second param will not get executed.
What you need to do is to define the function such a way that it will take 2 parameters then will multiply them and put the result to #demo element.
Then on click of the button, you can call the function with the desired parameters
<html>
<head>
<script>
function myFunction(a , b) {
document.getElementById("demo").innerHTML = a * b;
}
</script>
</head>
<body>
<p id = "demo"> </p>
<button type="button" onclick = "myFunction(3, 4)">Click me</button>
</body>
</html>
There are significant errors in this function definition:
function myFunction(a , b) {
return a * b;
document.getElementById("demo").innerHTML = myFunction(3, 4);
}
First, you call it using myFunction(), which assigns both a and b the value undefined; when you multiply them, you get NaN, which you return. When you return from a function, nothing else in the function gets executed. And if you didn't return, you would get into an infinite recursive loop (which would probably end in a stack overflow) as you keep calling the function from itself again and again.
These errors are the reason the script is not working; nothing to do with it being in the head.
Because you had return in myFunction and
document.getElementById("demo").innerHTML = myFunction(3, 4);
not executed. You could change into like this
<head>
<script>
function myFunction(a , b) {
return a * b;
}
function buttonClick() {
document.getElementById("demo").innerHTML = myFunction(3, 4);
}
</script>
</head>
<body>
<p id = "demo"> </p>
<button type="button" onclick = "buttonClick()">Click me</button>
</body>
Related
I am a Bit Beginner In JavaScript. So I need a code about { If we clicked a button a function need to run} more of them suggested this but it still not working ! and I don`t know why? Can you solve it?
if(document.getElementById("btn").clicked == true){
//some code here
console.log("working");
}
<button id=""btn>ClickEvent</button>
Do not use the if. if statement is executed on page load.
Instead, use Onclick() for example :
var data = "";
function clickBtn() {
if(data != "")
document.getElementById("result").innerHTML = "Hello World !";
else
getData();
}
function getData() {
data = "Hello World !";
}
<button onclick="clickBtn()">Click me</button>
<p id="result"></p>
Good question, lets use the an HTML file that references a JavaScript.
So the first file lets call it webpage.html
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="save" onclick="save()"></input>
<input type="button" value="display" onclick="print()"></input>
<div id="area"></div>
</body>
</html>
And the second file script.js
function save()
{
StringTest="Hello world";
}
function print()
{
document.getElementById("area").innerHTML=StringTest;
}
The approach might be a little different but this is recommended as you would more control over the elements in the script.
For example:
<input type="button" will tell the script that it is a form input of the type button whose click will call the function print() in the JavaScript
document.getElementById("area")captures the elements that we define from the Document Object Model(DOM)
This question already has answers here:
Setting a variable equal to a function without parenthesis? [duplicate]
(3 answers)
Closed 8 years ago.
In the following code, once I run it, it waits for click event to fire an alert. However if I change the following javascript code
from
clickMeButton.onclick=runTheExample;
to
clickMeButton.onclick=runTheExample();
it always fires up an alert when page downloaded without any click event. I would like to know what is the difference. I am using Chrome. Snipped code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
<script type="text/javascript" src="script13.js"> </script>
</head>
<body>
<h1 id="title">DOM Example </h1>
<p id="first">This is the first paragraph</p>
<p id="second"><strong>This is the second paragraph</strong></p>
<p id="third">This is the third paragraph</p>
<input type ="text" id="myTextBox" />
<input type ="submit" id="clickMe" value="Click Me!"/>
Google!
</body>
</html>
//script13.js
window.onload= function(){
var clickMeButton=document.getElementById('clickMe');
clickMeButton.onclick=runTheExample;
}
function runTheExample(){
alert('running the example');
}
var x = func(); //Means you execute the function and output its return value to x;
var x = func; //Means you attribute the function to the variable, so you can call it, using x.
Example
function f(){
return 4;
}
var x = f(); // x = 4
var x = f; // x = f()
I am very new to JavaScript and cannot seem to get the setTimeout command to do anything. I know this has been asked many times before, but I have spent the last two hours looking at all previous cases of it and it still isn't working for me. Here is what I have got at the moment:
<html>
<script type="text/javascript">
var i = 0;
function aloop() {
document.write(i);
i++;
}
function afunction() {
if (i <= 12) {
setTimeout(aloop(), 1000);
afunction();
}
}
</script>
<form>
<input type=submit value="Click me!" onClick="afunction()">
</html>
Can anyone tell me what I should do to make this work?
Pass a function to setTimeout, not the return value of a function call.
setTimeout(aloop,1000);
The problem is you're calling your function instead of queuing your function.
setTimeout(aloop, 1000) NOT setTimeout(aloop(), 1000);
You didn't describe what doesn't work, but I'll assume you want the i to be written in 1000 millisecond intervals.
Do this:
<html>
<!-- you're missing your head tags -->
<head>
<title> my page </title>
<script type="text/javascript">
var i=0;
function aloop() {
// don't use document.write after the DOM is loaded
document.body.innerHTML = i;
i++;
afunction(); // do the next call here
}
function afunction() {
if (i<=12) {
// v---pass the function, don't call
setTimeout(aloop,1000);
// afunction(); // remove this because it'll call it immediately
}
}
</script>
</head>
<!-- you're missing your body tags -->
<body>
<form>
<input type=submit value="Click me!" onClick="afunction()">
</form> <!-- you're missing your closing form tag -->
</body>
</html>
Supposed to insert entered text between input field and send button, but it does noting.
<body>
<section>
<p>passcode: <input type=text id=passcode></p>
<section id=middle></section>
<p><input type=button id=button value=send></p>
</section>
<script type="text/javascript">
var log=new Array();
document.getElementById("button").onclick=exlog();
exlog(){
log.push(document.getElementById("passcode").value)
for(i=0;i<log.length;i++){
document.getElementById("middle").innerHtml=log[i];
}
}
</script>
</body>
Change
document.getElementById("middle").innerHtml=log[i];
to
document.getElementById("middle").innerHTML=log[i];
Reference: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
Your exlog function is missing the function keyword and you are setting the onclick handler incorrectly.
Also innerHtml should be innerHTML
document.getElementById("button").onclick=exlog;
function exlog(){
log.push(document.getElementById("passcode").value)
for(i=0;i<log.length;i++){
document.getElementById("middle").innerHTML=log[i];
}
I noticed a couple of problems with your code. Most importantly, you should use innerHTML, not innerHtml (note capitalization).
Additionally, you need to be careful of how you deal with functions. Just putting exlog(){} will not create a function. Instead, you should use the function keyword.
Finally, you want to set the onclick handler to the function exlog. What you have used will actually set the onclick handler to the result of evaluating the exlog function.
Here's a solution with all of the suggested changes:
<body>
<section>
<p>passcode: <input type=text id=passcode></p>
<section id=middle></section>
<p><input type=button id=button value=send></p>
</section>
<script type="text/javascript">
var log=new Array();
document.getElementById("button").onclick=exlog;
function exlog(){
log.push(document.getElementById("passcode").value)
for(i=0;i<log.length;i++){
alert(log[i]);
document.getElementById("middle").innerHTML=log[i];
}
}
</script>
</body>
You are evaluating the function by using it like this: exlog(), since exlog doesn't have a return statement, it evaluates to undefined, which the browser won't execute.
If you want to assign it you can just use it's name exlog
Also, as mentioned by Teemu and Musa, the function keyword was missing from the definition of exlog
Also, the capitalization of innerHTML has to be exact, mixing cases wont work.
<body>
<section>
<p>passcode: <input type=text id=passcode></p>
<section id=middle></section>
<p><input type=button id=button value=send></p>
</section>
<script type="text/javascript">
var log = [];
document.getElementById("button").onclick = exlog; // <== no need to evaluate the function, just assign it.
function exlog(){ // <== as pointed out below function keyword was missing
log.push(document.getElementById("passcode").value);
document.getElementById("middle").innerHTML += log[log.length - 1]; // <== needs to be capitilized exactly like this
}
</script>
</body>
I have a number of links, that when clicked on, passes a variable thru to another portion of the page.
Yet, for some reason, I can’t figure it out! What am I missing?
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
return myid;
}
</script>
</head>
<body>
Click Me<br />
<script type="text/javascript">
document.write(myid);
</script>
</body>
You are getting a little mixed up here. Even though the function returns a value, it has nothing to return it to. Try this:
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
document.getElementById("debug").innerHTML = myid;
}
</script>
</head>
<body>
Click Me<br />
<div id="debug"></div>
</body>
if you want to use it later you need to declare myid as a global variable. its scope is currently only within myFunction. also the document.write() function will only execute at runtime so you need to have another function the executes that with every click, or just combine the two.
When you click the link all that happens is that the myFunction() is called which returns the string. The line document.write(myid); is not executed anymore so nothing is visible.
<script>
// This is global
var myid = ''
myfunc = function(a){
myid = "Hi There!" + a;
alert(myid);
}
test_global = function(){
alert(myid);
}
</script>
Set MYID
<input type="button" onclick="test_global();" value="Test MYID" />
Here is a simple example of some similar stuff:
clickme or ClickMeAlso
<input id='other' type='text'/>
<script>
function myfunc(a) {
return a + " howdy";
};
</script>
You can see this in action here:http://jsfiddle.net/5Sbn2/