I need to be able to create a seperate function which creates a total figure from variables within 2 different functions.
function addToy1()
{
var i = document.getElementById("qty_toy1");
var qtytoy1 = i.options[i.selectedIndex].text;
var qtytoy1tot = qtytoy1 * 26.99;
var generateTableToy1="<table width=\"210px\" border=\"0\">"
+" <tr>"
+" <td width=\"140\">Optimus Prime</td>"
+" <td width=\"25\">x " + qtytoy1 + "</td>"
+" <td width=\"45\">£" + qtytoy1tot + "</td>"
+" </tr>"
+"</table>";
document.getElementById("toy1_add").innerHTML=generateTableToy1;
}
function addToy2()
{
var i = document.getElementById("qty_toy2");
var qtytoy2 = i.options[i.selectedIndex].text;
var qtytoy2tot = qtytoy2 * 14.39;
var generateTableToy2="<table width=\"210px\" border=\"0\">"
+" <tr>"
+" <td width=\"140\">Bumblebee</td>"
+" <td width=\"25\">x " + qtytoy2 + "</td>"
+" <td width=\"45\">£" + qtytoy2tot + "</td>"
+" </tr>"
+"</table>";
document.getElementById("toy2_add").innerHTML=generateTableToy2;
}
With this code I need to make a sum of both variables “qtytoy1tot” and “qtytoy2tot”. I am new to Javascript. Please help where you can. Thanks.
You have a number of options here. The most straight forward is as Amit suggested in the comment, just return the total from each of the methods. This may or may not work depending on how you plan on using these methods. Something like the following should work for your purposes.
Keep in mind, you really just have one function here, and you should pass in the variable parts in as parameters to the function, but I think that may be beyond the scope of this question.