+ 6
javascript take a returned value
if i have a function like; function MyFunction(a, b){ var c=a+b; return c; } how can i use the returned value(c) in another function?
55 Antworten
+ 4
if you don't want prompt() each time you call your function, you must separate it in 2 functions:
function getUserValue(msg="") {
return prompt(msg);
}
function doDomething(a,b) {
var c = a+b;
return c;
}
var userValue = +getUserValue("give me a number:");
var result1 = doSomething(userValue,1);
var result2 = doSomething(userValue,-1);
console.log(result1+" "+result2);
+ 2
let returned_value = MyFunction(1,2);
function mult_by_3(n){
return n*3;
}
alert(mult_by_3(returned_value));
+ 1
actually, your code use the wrong button to do what you're expect ;)
+ 1
yes...
you should move the onclick attribute from the wrong button to the right one ;)
+ 1
this one:
<button type="button" onclick="userAge" name="button" checked>controllo</button>
you must use the onclick event to call the control fubction instead of 'userAge', and remove it from the other button...
+ 1
I've edited my code to correct the behavior ;)
+ 1
check it again: you may have not seen the changes... try to click the contollo button to be convinced ^^
+ 1
well, it was not clear (and I don't know if I've got it)...
if I correctly understood, you must wrap the assignement to age variable inside a function (but declare the variable outside to be accessible from anywhere) and call it from the controllo button...
check my updated code and let me know if the behavior is the one expected ;)
+ 1
Yes it works, now i "just" need to solve other 2 things
+ 1
Eseosa Osasu Arasomwan
don't post in unrelated thread with your question ^^
I see from your profile that you have subscribed from less than one hour: you must be patient ;P
0
you can store the returned value in a variable:
var result = MyFunction(3,4);
console.log(result); // 7
0
@vishp i already did it but the problem is that my function is also used for take an input with prompt, so if i write var x= MyFunction(); the prompt will appear
0
take the value once, saving it in a variable, then you could do what you want with it (without always prompting user for a value) ^^
0
share your whole real code to get accurate answer according to your use case ;P
0
@vishp i made it in another file for test but the output doesnt work
0
just a typo, i fixed it
0
what do you use for output?
console.log() output to console
alert() output in popup modal window (as prompt)
document.write() output in html document (create a new one if called after onload event)
element.textContent = 'text content' output in element (must be initialized with the target element)
element.innerHTML = 'some <b>html</b> text' output also in element, but parse the value as html code
0
ok: forgot my last post if you want ;)
0
@vishp but i need to start the variable for get message inside a button with onClick, i think that i declare a variable inside a button, is it right?
0
i solved it