I need to write a quick bit of code that allows users at the top of one of our article pages to do the following:
Drop down 1: How old are you?
Drop down 2: What's your favourite fruit?
Based on inputs above, summary text instantly displays below after the second selection is made, based on both selections above e.g.
For 18-24 year olds who like apples: Apples help you build your immune system at your age!
For 50-60 year olds who like bananas: Bananas really help with vitamin C and bone density in later life.
It all depends on how your data is structured.
Assuming that there is going to be quite a few ages and fruits, some sort of data structure like this would work:
var text = [
{ fruit: "bananas", ages:
[
{ range: "18-24", text:"Bananas are awesome"},
{ range: "50-60", text:"Bananas really help with vitamin C and bone density in later life."}
]
},
{ fruit: "apples", ages:
[
{range: "18-24", text:"Apples help you build your immune system at your age!"},
{range: "50-60", text:"Apples are cheap."}
]
}
]
Then the selected value of the select lists can be used to search the data for the right text:
function findText(fruit,age)
{
for(var i =0; i < text.length; i++)
{
if(text[i].friut == fruit)
{
for(var j=0; j < text[i].ages.length; j++)
{
if(text[i].ages[j].range == age)
return (text[i].ages[j].text;
}
}
}
return "No match";
}
Then how ever you bind the change events just call the find function:
document.getElementById("age").onchange = function()
{
var age= document.getElementById("age").value();
var fruit = document.getElementById("fruit").value();
var displayText = fruitText(friut,text);
}