Pls how do I add this two functions I declared and store into another function(a third function) so I will be able to call the addition of the result of both functions using the third function?
function myFunc() { var grade1 = document.getElementById("grade").value; var unit = 3; var tUnits = 18; switch (grade1) { case 'a': document.getElementById('demo').innerHTML = (5 * unit / tUnits); break; case 'b': document.getElementById('demo').innerHTML = (4 * unit / tUnits); break; default: document.getElementById('demo').innerHTML = 'Please input a valid grade'; } return grade1; } function myFunc2() { var grade2 = document.getElementById("grade2").value; var unit2 = 3 var tUnits = 18 switch (grade2) { case 'a': document.getElementById('demo').innerHTML = (10 * unit2 / tUnits); break; case 'b': default: document.getElementById('demo').innerHTML = 'Please input a valid grade'; } }
That is the code above!
Advertisement
Answer
Change your functions so they return the result instead of putting it in innerHTML
. Then you can have another function that calls both of them and displays both results.
function myFunc() { var grade1 = document.getElementById("grade").value; var unit = 3; var tUnits = 18; switch (grade1) { case 'a': return (5 * unit / tUnits); break; case 'b': return (4 * unit / tUnits); break; default: return 'Please input a valid grade'; } } function myFunc2() { var grade2 = document.getElementById("grade2").value; var unit2 = 3 var tUnits = 18 switch (grade2) { case 'a': return (10 * unit2 / tUnits); break; case 'b': default: return 'Please input a valid grade'; } } function combinedFunc() { let class1 = myFunc(); let class2 = myFunc2(); document.getElementById("demo").innerText = `Class 1: ${class1}, Class 2: ${class2}`; }
<select id="grade"> <option value="">Grade for Class 1</option> <option value="a">A</option> <option value="b">B</option> </select> <select id="grade2"> <option value="">Grade for Class 2</option> <option value="a">A</option> <option value="b">B</option> </select> <button type="button" onclick="combinedFunc()">Show Grades</button> <p> Grades: <div id="demo"></div>