Reputation: 407
A rather trivial question, how do I return or pass a value outside the function?
Code below:
function numberOfDivs(){
var numberOfElements = $("#div").children().length; //this count how many divs exist
return numberOfElements;
}
$("#element").click(function(){
numberOfDivs();
console.log(numberOfElements);// here I need to return the number but getting error :(
});
many thanks
Upvotes: 0
Views: 57
Reputation: 822
Try using Callback functions, consider a scenario where incase your numberofDivs function takes time to return the value, it will not give the appropriate results as Jquery is an asynchronous. See this demo for the use of callback to return the data CALLBACK DEMO
function AppendJson(callback) {
var numberOfElements = "AppendJson";
callback(numberOfElements)
}
AppendJson(function (ReturnValue) {
alert(ReturnValue);
});
Upvotes: 1
Reputation: 20840
One way is : define numberOfElements
in global scope like this :
var numberOfElements;
function numberOfDivs(){
numberOfElements = $("#div").children().length; //this count how many divs exist
return numberOfElements;
}
$("#element").click(function(){
numberOfDivs();
console.log(numberOfElements);// here I need to return the number but getting error :(
});
Or another way is : assign the result in one variable and use that
$("#element").click(function(){
var output = numberOfDivs();
console.log(output);// here I need to return the number but getting error :(
});
Upvotes: 1
Reputation: 10553
Try
var numberOfElements= numberOfDivs();
console.log(numberOfElements);
As the function is to return a value, while we invoke the function we assigned a variable to capture the result
Upvotes: 2
Reputation: 3574
var numberOfElements;
function numberOfDivs(){
numberOfElements = $("#div").children().length; //this count how many divs exist
}
$("#element").click(function(){
console.log(numberOfElements);// here I need to return the number but getting error :(
});
Upvotes: 1
Reputation: 22619
$("#element").click(function(){
var numberOfElements= numberOfDivs();
console.log(numberOfElements);
});
Upvotes: 2