I have a web form where users answer questions via dropdowns, and I wish to make other questions available based on their responses.
e.g. if your business has a premises then ask about opening hours. If they don’t, show the regions they operate in.
With each question I add to the process, the more complex the code becomes. A lot of if/then functions that don’t always have mutually exclusive answers.
Whilst each user may only have to answer 5-10 questions, the number of possible questions can be 100+.
Is there a simple way to generate either Javascript/PHP or at the very least pseudo code which lets you plot a path through all the available answers and it generates the relevant nested if/then statements for you?
Example: Akinator guesses TV characters based on previous answers.
In anticipation of certain responses, of course the page doesn’t have to be coded so that all questions are answered on one page, but I want to know if it’s at least possible.
Thanks in advance. I hope you all enjoy WWDC 😉
Advertisement
Answer
You can set up a json object on the page that contains all of the rules and on each element have an id/attribute that corresponds to the json object. Then on change you check the json object for a “trigger” node that corresponds to the “change” element’s attribute and then find all the elements that should be hidden/shown based upon that value. Note this code is really rough and not an exact answer but enough of an idea to get you started.
<select id='q1' onchange='handleHideShow(this)'></select> <select id='q2' onchange='handleHideShow(this)'></select> function handleHideShow(el) { var elValue = el.value; if(hsObj[el.id]) { var rules = hsObj[el.id].rules; for(var r = 0; r < rules.length; r++) { var rRule = rules[r]; for(var t in rRule) { var showEl = document.getElementById(rRule[t]); if(showEl) { var hideVal = ""; if(elValue != t) { hideVal = 'none'; } showEl.styles.display = hideVal; } } } } } var hsObj = [ "q1":{"Yes":"q2"} ];