I wanted to have a Simple PreLoaded Html Mobile Quiz that shows one question on a screen at a time via jQuery using showing/hiding divs
The problem comes when the user needs to skip over a question or two,
I wanted to do this by setting flags if I should show that div or not
based on the users select/option value/answer
I have found solutions on here, but what I really need is a simple
way with flags to know if the next div should be showed or not
q2skipped=true or q2skipped=false
if it’s not shown, then it would go to test q3skipped flag
I made a example in jsfiddle here:
<div class="question" id="question1">Q.1 Do you like Milk
<select name="1" onchange="displayElements(this.value);" >
<option value="yes">Yes</option>
<option value="no">No</option>
<option >Goto Next Question</option>
<option value="q2skipped=true">Skip Next Question</option>
<option value="q2skipped=true;q3skipped=true">Skip Next 2 Questions</option>
</select><br>
<div>
<input type="submit" id="button" value="Submit" onclick='doSubmit(this)'>
</div>
</div>
It seems a more repeatable approach is warranted. Hardcoding all values for all questions is an annoying task, and you’ll have to repeat that if you ever have to create a new quiz.
I don’t understand the full scope of your application, but I’ll give you some general tips to help you get on the path to a cleaner solution.
(1) Style your questions by using classes. For example, you could use the following CSS:
CSS will be irrelevant if you hide the questions after being answered, but it does help demonstrate my point.
(2) Refrain from using hardcoded values in the HTML (except of course the question number) Something like:
I see you using
id="button"on the submit button. This is a fairly bad idea since an ID should be unique. The best way is to not mention an ID on the button if you don’t need it.Also note that the button’s onclick event now passes the ID of the question. It’ll become clear later on.
I added an “answer” class to the select so you can easily retrieve the user’s answer later on.
I also left out the onclick and name attributes with the select button. I’m not sure what the onclick event should do (unrelated to this question?) And the name attribute doesn’t really seem necessary here (again, if it’s needed by something that isn’t mentioned in this question, you can add it again).
(3) Use javascript/jQuery to define what should happen.
This should get you further in building a repeatable process for handling the user’s answers. I hope I was able to make it clear enough so you understand; if not, feel free to ask 🙂