Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Simple Javascript Questionaire */
- /*
- In response to a Yahoo Answers Question.
- To be used with: http://pastebin.com/b6U3L4D8
- */
- var questions = [];
- questions[0] = {'question': 'What is your Age', 'answers': ['13-18','19-24','25-35','35-50','50+'], 'answer': ''}; // Answer Will Hold the User's Selection
- questions[1] = {'question': 'What is your favourite color', 'answers': ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple'], 'answer': ''};
- questions[2] = {'question': 'What is your favourite pet', 'answers': ['Dog','Cat','Rodent','Reptile','Fish'], 'answer': ''};
- var curQ = 0;
- var ques = questions[curQ];
- function echo(s){ console.log(s); }
- function byId(id){
- return document.getElementById(id);
- }
- function checkForAnswer(){
- var ab = byId('answersBox');
- var inputs = ab.getElementsByTagName('input');
- var answer = '';
- if(inputs.length === 0){ return true; }
- for(x in inputs){
- if(inputs[x].checked){ answer = inputs[x].value; }
- }
- ques.answer = answer;
- return (answer.length > 0);
- }
- function switchQ(v){
- if( (checkForAnswer() && v > 0) || v < 0 ){
- curQ += v;
- displayQuestion();
- }else {
- alert("Question Must Be Answered Before Proceeding");
- }
- }
- function disableEnableBtns(){
- byId('prevQBtn').disabled = (curQ === 0);
- byId('nextQBtn').disabled = ( curQ === (questions.length - 1));
- byId('resultsQBtn').disabled = (curQ !== (questions.length - 1));
- }
- function displayQuestion(){
- if(curQ < 0) { curQ = 0; }
- if(curQ >= questions.length){ curQ = questions.length - 1;}
- disableEnableBtns();
- ques = questions[curQ]; // Current Question Object
- var qb = byId('questionBox'); // Question Box
- var ab = byId('answersBox'); // Answers Box
- qb.innerHTML = ques.question + '?';
- ab.innerHTML = 'Select One of the follow:<br>';
- for( i in ques.answers){
- ab.innerHTML += '<input type="radio" name="theAnswer" value="' + questions[curQ].answers[i] + '">' + questions[curQ].answers[i] + '<br>';
- }
- /* Check for a current Answer */
- if(ques.answer.length > 0){
- ab.innerHTML = ab.innerHTML.split('value="' + ques.answer + '"').join('value="' + ques.answer + '" checked="checked"');
- }
- }
- function displayResults(){
- if(!checkForAnswer()){
- alert('Please answer the last question before seeing the results');
- }else{
- var html = '';
- for( i=0;i<questions.length;++i){
- html += '<span style="font-weight: bold;">' + questions[i].question + '?</span> ' + questions[i].answer + '<br>';
- }
- byId('questionBox').innerHTML = 'Results';
- byId('answersBox').innerHTML = html;
- }
- }
- window.onload = function(){ displayQuestion(); }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement