json - Displaying questions for a quiz using javascript -
i doing javascriptissexy.com learning path. having trouble figuring out best way display quiz questions. question beginner javascript student. how should tackle approach of developing behavior of quiz app. if @ code have stored questions in json. how can display questions user or can answer question , interact program?
var questions = [{ questions: "what name of biggest part of human brain?", choices : ["cerebrum", "thalamus","medulla", "cerebellum"], correstanswer: 0 }, { questions: "the colored part of human eye controls how light passes through pupil called the?", choices: ["pupil", "rods", "iris", "cornea"], correctanswer: 2 }, { questions: "what name of substance gives skin , hair pigment?", choices: ["dermis", "melanin", "swear gland", "epiderms"], correctanswer: 1 }, { questions: "the muscles found in front of thighs known what?", choices: ["adductor", "petella", "tibia", "quadriceps"], correctanswer: 3 }, { questions: "15. shape of dna known as?", choices: ["double helix", "adenine helix", "tri helix", "thymine"], correctanswer: 0 }, { questions: "a structure composed of 2 or more tissues termed?", choices: ["serous membrane", "complex tissue", "organ system", "organ"], correctanswer: 3 }, { questions: "the heart ____ lungs?", choices: ["superior", "dorsal", "medial", "lateral"], correctanswer: 2 }, { questions: "male hormones produced of following?", choices: ["prostate", "testes", "vas deferens", "prepuce"], correctanswer: 1 }, { questions: "which of following terms describes body's ability maintain normal state?", choices: ["anabolism", "catabolism", "tolerance", "homoestasis"], correctanswer: 3 }, { questions: "each of following known prevent infection except?", choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"], correctanswer: 3 } ]; /* * question variables */ var currentquestions = 0; var currentanswer = 0; var quizdone = false; $(document).ready(function(){ /* * show current question */ displayquestions(); function randomize(questions) { var currentindex = questions.length; var tempquestion, randomindex; //pick remaining element while (currentindex > 1 ) { randomindex = math.floor(math.random() * currentindex); currentindex -= 1; tempquestion = question[currentindex]; questions[currentindex] = questions[randomindex]; questions[randomindex] = tempquestion; } return questions; } });
my codepen link https://codepen.io/oa11an/pen/jvwmey?editors=0010
i had started writing before henrydev's answer, , though saw finished , answer accepted, figured information read regardless
there's basic coding philosophy many people use , go by, , few different versions. it's called model-view-controller (mvc) short. tries split code distinct chunks not end many people refer "spaghetti code" (code just... everywhere).
the basics of this, , please before pitchforks go these my understandings of mvc have picked through years, if not verbatim you say, don't lynch me it, followed:
model
the entire point of model , solely responsible getting data. whether or not data using quiz questions/answers, random numbers generated on page, airline info, whatever. model of code stored.
each type of model in code should have different model object / class (depending language using). in case have questions
model, aka aggregate collection of of questions, , question
(note, no 's', singular). questions
job pull correct question
objects wherever store them. approach vary depending on system make using (mean stack, lamp stack, insert list of thousand different applicable stacks use). question
job store relevant data one question (the question, it's answer choices, correct answer, etc.)
view
the view in charge of taking data model , doing 2 things
- displaying way logical. varies heavily case case. basic idea follow wouldn't display blog post same way i'd display navigation menu. depends on showing. before start view biggest suggestion think makes sense this.
- linking actions controller modify or change data.
controller
the controller kind of big boss in of this, though listed last. controller logic machine behind of work since model's job data, , view's main job show data, controller of application logic should go. decides models should used, , times a (there can more one) controller decides view should shown.
with of in mind, here basic setup did right now. (quick thing, used jquery , bootstrap make pretty minimal effort on part).
$(function() { //this notation jquery calls function when dom ready or page has loaded. can never remember. use short hand $(document).ready totally wrong. //because read beginner in javascript, let's assume our questions array basic model. //and each object in array question model. once more practice, should make lot more sense. var questions = [{ questions: "what name of biggest part of human brain?", choices: ["cerebrum", "thalamus", "medulla", "cerebellum"], correctanswer: 0 }, { questions: "the colored part of human eye controls how light passes through pupil called the?", choices: ["pupil", "rods", "iris", "cornea"], correctanswer: 2 }, { questions: "what name of substance gives skin , hair pigment?", choices: ["dermis", "melanin", "swear gland", "epiderms"], correctanswer: 1 }, { questions: "the muscles found in front of thighs known what?", choices: ["adductor", "petella", "tibia", "quadriceps"], correctanswer: 3 }, { questions: "the shape of dna known as?", choices: ["double helix", "adenine helix", "tri helix", "thymine"], correctanswer: 0 }, { questions: "a structure composed of 2 or more tissues termed?", choices: ["serous membrane", "complex tissue", "organ system", "organ"], correctanswer: 3 }, { questions: "the heart ____ lungs?", choices: ["superior", "dorsal", "medial", "lateral"], correctanswer: 2 }, { questions: "male hormones produced of following?", choices: ["prostate", "testes", "vas deferens", "prepuce"], correctanswer: 1 }, { questions: "which of following terms describes body's ability maintain normal state?", choices: ["anabolism", "catabolism", "tolerance", "homoestasis"], correctanswer: 3 }, { questions: "each of following known prevent infection except?", choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"], correctanswer: 3 }]; // end questions //many people use called angular, it's javascript library sort of... links view/model sections nicely. since learning, leave out , via straight jquery. var question_container = $('#questions-container'); //grabs question container, aka our form. question_container.on('submit', function(e) { e.preventdefault(); //let's stop default event. var questions = $(this).children('.question'); //this gets each question questions.each(function(i, el) { var $el = $(el); //i short hand. default element passed down html object, , not jquery object. use notation keep getting myself confused var selected = $el.find(':checked'); //this looks through our html find child element of question element have selected; $el.toggleclass('bg-danger', selected.val() != $el.data('answer')); //this toggles class borrowed bootstrap, bg-danger, if value not equal our answer $el.toggleclass('bg-success', selected.val() == $el.data('answer')); //this toggles success class, bg-success, if value equal answer have stored }); }) $.each(questions, function(i, question) { var container = $('<div class="question">'); //creates new div class of 'question' var qheader = $('<h3>').html(question.questions); // creates, , assigns html , h3 element header of our question var ul = $('<ul class="list-unstyled">'); //creates new list answers set down, class of 'list-unstyled' container.data('answer', question.correctanswer); //this jquery thing stores correct answer on container (div.question) don't have loop through questions after questions. question_container.append(container.append(qheader)); //appends our current container form have above $.each(question.choices, function(j, choice) { //jquery function, loops through choices in current question. notice used j here instead of avoid confusion $.each call above var item = $('<li> ' + choice + '</li>'); //creates new list item text answer inserted var radio = $('<input type="radio" name="question[' + + ']" value="' + j + '" />'); //creates radio button, specific name , value. check outcome of html , feel free fiddle if don't understand why did did here. radio.prependto(item); //prepends radio element li appears before choice text item.appendto(ul); //adds li item our list, created above. }); // end $.each(question.choices); ul.appendto(container); //adds ul our container }); //end $.each(questions); }) //end $()
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>let's take quiz!</h1> <div class="questions container"> <form action="your_page_here.php" id="questions-container"> <input type="submit" class="btn btn-success" /> <input type="reset" class="btn btn-info" /> </form> </div>
edit
here link codepen developed on, because of sandboxing snippet editor on browsers code doesn't seem work.
Comments
Post a Comment