Pass a value from function to other functions in Javascript
Pass a value from function to other functions in Javascript
Asked 6 years, 5 months ago Modified 6 years, 5 months ago Viewed 1k times
I need to get a value from an HTML input in a javascript function. I can successfully get the value form the HTML but I
couldn't pass that from 1 function to other. And I need to pass that value to other function that is available on that javascript.
0 I tried this code I'm getting undefined.
This is my script with the main function, and I can get the value from the HTML:
javascript function
Share Improve this question Follow edited Jul 11, 2018 at 23:05 asked Jul 11, 2018 at 21:13
Vahid Boreiri ANZR
3,438 1 20 34 ANZR 91 1 2 9
Possible duplicate of How to return values in javascript – Guillaume Georges Jul 11, 2018 at 21:40
Customize settings
If you want to pass the value that you get in PageKey to some other function, you need to add a return statement to
PageKey .
2
var PageKey = function(){
return document.getElementById('demo').value;
}
Share Improve this answer Follow answered Jul 11, 2018 at 21:22
Ovid2020
181 10
The data parameter in fun1, fun2 functions should be holding the value of val – ANZR Jul 11, 2018 at 21:49
Setting a parameter to hold a value in a function expression doesn't make sense... the function expression is saying "I want this logic that
I'm calling fun1 to accept some input and do something with it (and then maybe return some output)". You would then pass an argument
( data , in this case) to it at runtime. That'd look something like fun1(fun3(PageKey())) , after you have added a return statement to
fun3 . Or, if you're sure you want a function to have a parameter stored with certain value, you would use bind : var boundFun1 =
fun1.bind(null, data); – Ovid2020 Jul 11, 2018 at 23:12
^^ but I don't think that's what you're trying to accomplish, since you could do that in a way simpler expression. What are you trying to
make happen, here, on a top level? I want to make sure I'm understanding the question – Ovid2020 Jul 11, 2018 at 23:13
PageKey() is just getting the value, but it does not return it. So, you need to add return val; to PageKey() . Then, in fun3,
you can set a variable to what's returned from PageKey() . So, you would end up with this:
2
var PageKey = function(){
var val = document.getElementById('demo').value;
return val;
}
this works fine. But the data parameter in fun1, fun2 functions should be holding the value of val – ANZR Jul 11, 2018 at 21:45
Ah, in that case we need to call fun1 and fun2 inside of fun3. I've updated my answer to reflect this. – Ryan Z Jul 11, 2018 at 22:57
You have to return the value
And then
Share Improve this answer Follow answered Jul 11, 2018 at 21:18
user6749601