Mesotu
Mesotu

Reputation: 31

Javascript for survey

Background I'm working on a survey in javascript which contains ten "yes" or "no" questions. I'd like to code the "yes" responses to = 1 and the "no" responses to = 0. I'm using the html tag so they can only choose one or the other.

Then I'd like to have the sum of their responses added up and divided by the total number of questions to yield a percentage. Depending on their percentage, I would then like to output some HTML text to a field below it with some helpful tips and advice relevant to their score.

To be clear, though I'm learning javascript now, I don't expect anyone to code the thing for me, but I'd just like to know where I should be looking for answers to make this happen. I'm thinking I need to use the if/else conditions to account for the yes/no responses and then maybe I need another function() to do the rest of the calculations.

I've tried a number of different variations of if/else statements but I'm just confused about how to 1) code the yes/no responses; 2) integrate them into if/else statements.

I'll add an abbreviated snippet of code with two sample questions that I'm trying to get working now.

function calc (form) {
var score1;
var score2;
var Result = form.Result.value;


if (form.Question1.options[form.Question1.selectedIndex].value =    "Yes") { score1 = 1;
 } else {
 score1 = 0;
 }

if (form.Question2.options[form.Question2.selectedIndex].value = "Yes") {  score2 = 1;
 } else {
 score2 = 0;
 }

Result = (((score1 + score2) / 10) * 100);

if (Result == 80) {
 document.getElementById("recommendation").innerHTML = "<h4>Heading here</h4> <p>Advice goes here based on their result</p>"
   }  
 }

Upvotes: 1

Views: 1510

Answers (2)

Icepickle
Icepickle

Reputation: 12796

To be fair, I believe you need to rethink your approach. Having an if-then-else approach for each question & answer can be quite tedious in maintaining or when you want to change the answers.

If you would create a data structure for your questions, you could use for-loops or saving indexes of the current question to handle an answer. The correct answer would then also be part of your data structure (but that is up to you, it could be a client/server request as well).

You already got some answers why your current approach doesn't work due to missing up assignment with equality operators, but I thought I would give you an alternative solution.

This solution will create a dynamic ui, and handle answers on questions when the next button is clicked. The questionaire here is unidirectional, you can only go forward :)

It is mainly to give you an idea how to approach it differently. I don't imagine you actually using this code as is.

The code has quite some inline comments, and is based on the usage of a generator function (which are not supported by Internet Explorer, but should be fine in any other browser)

Upon completion, the score would be displayed in a message box.

// data structure that takes question / answer / which is correct and the points attributed
const questions = [
  { 
    question: 'What platform are you on?',
    answers: ['Stackoverflow', 'codereview'],
    correct: 0,
    points: 5
  },
  { 
    question: 'What is the answer to everything',
    answers: [42, 'I don\'t have a clue'],
    correct: 0,
    points: 1
  },
  { 
    question: 'How much is 7*6',
    answers: ['I am not good with maths', 42],
    correct: 1,
    points: 10
  }
];

// a simple generator that is used in the questionaire
function *questionsGenerator( questions ) {
  yield* questions;
}

// creates a questionaire, with forward only options (due to the use of the generator function)
// all variables are locally scoped, when all questions were answered, the onCompleted callback would be called
// it returns an object with nextQuestion function though it could call nextButton internally, and you just have to call the function once if you would want to change it
const questionaire = ( query, nextButton, target, onCompleted ) => {
  let score = 0;
  let iterator = questionsGenerator( query );
  let question = null;
  let selectedAnswer = -1;
  
  nextButton.addEventListener('click', nextQuestion);
  
  function evaluateAnswer() {
    if (!question) {
      // no question yet
      return;
    }
    if (selectedAnswer < 0) {
      return;
    }
    if (question.correct === selectedAnswer) {
      score += question.points;
    }
    return;
  }
  
  function nextQuestion() {
    evaluateAnswer();
    question = iterator.next();
    // this is a bit of a hack to check if we just had the last question or not
    if (question.done) {
      nextButton.removeEventListener('click', nextQuestion);
      onCompleted( score );
      return;
    }
    question = question.value;
    drawUI();
  }
  
  function drawUI() {
    // disable next button
    nextButton.setAttribute('disabled', true);
    selectedAnswer = -1;
    // remove existing items
    Array.from( target.childNodes ).forEach( child => target.removeChild( child ) );
    // create new questions (if available)
    const title = document.createElement('h1');
    title.innerHTML = question.question;
    target.appendChild( title );
    
    question.answers.map( (answer, i) => {
      const el = document.createElement('input');
      el.type = 'radio';
      el.name = 'answer';
      el.value = i;
      el.id = 'answer' + i;
      el.addEventListener('change', () => { 
        selectedAnswer = i; 
        nextButton.removeAttribute('disabled'); 
      } );
      const label = document.createElement('label');
      label.setAttribute('for', el.id );
      label.innerHTML = answer;
      
      const container = document.createElement('div');
      container.appendChild(el);
      container.appendChild(label);
      return container;      
    } ).forEach( a => target.appendChild( a ) );
  }
  
  return {
    nextQuestion
  }
};

// create a questionaire and start the first question
questionaire(
  questions, 
  document.querySelector('#btnNext'), 
  document.querySelector('#questionaire'), 
  score => alert('You scored ' + score ) 
).nextQuestion();
<div id="questionaire">
</div>
<div class="toolstrip">
<button id="btnNext" type="button">Next</button>
</div>

Upvotes: 1

Laczk&#243; &#214;rs
Laczk&#243; &#214;rs

Reputation: 1118

If you want to check for equality use == or ===. == will check if the values are the same, === will also check if the types are the same.

For example:

0 == "0" => true 

0 === "0" => false.

Upvotes: 0

Related Questions