Triva Game, compare radio buttons value to answer - javascript

I'm creating a Trivia game using an array of objects. I created a function that loops through and displays all the questions and then loops through all the choices and turns them into radio buttons. I've been struggling comparing the answer to the selected value, so when the timer runs out I can print how many the user got right and wrong. Can someone point me to correct direction?
function countdown() {
var counter = 60;
var timeCountdown = setInterval(function(){
counter--
$('.timer-container .time').html(counter);
if (counter === 0) {
clearInterval(timeCountdown);
$('.timer-container .time').html("Times Up");
points();
}
}, 1000);
$('.timer-container').toggle();
}
let trivia = [
{
question: "How many wheels are on a skateboard?",
choices: ["2", "4", "6", "8"],
answer: "2",
},
{
question: "Who invented the kickflip?",
choices: ["Tony Hawk", "Bam Magera", "Rodney Mullen", "Chad Muska"],
answer: "Rodney Mullen"
},
{
question: "Who did the first 900?",
choices: ["Tony Hawk", "Tas Pappas", "Danny Way", "bob burnquist"],
answer: "Tony Hawk",
},
{
question: "What is another word for a 360 flip?",
choices: ["Impossible Flip", "3 1/2 flip", "Tre Bomb", "Tri Flip"],
answer: "Tre Bomb",
}
];
function triviaQuestions() {
for(var i = 0; i < trivia.length; i++) {
var questionHeader = $('<h2 class="question-' + i + '">');
var questionHeaderContent = questionHeader.text(trivia[i].question);
$('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + " '>");
for (var j = 0; j < trivia.length; j++) {
console.log(trivia[i].choices[j]);
var questionChoices = $('<input type="radio"' + 'name="' + i + '"'+ 'value="' + trivia[i].choices[j] + '">' + '<label>' + trivia[i].choices[j] + '</label>');
var questionChoicesContent = questionChoices.text(trivia[i].choices[j]);
$('.choices-container-' + i).append(questionChoices).append(questionChoicesContent);
}
}
}
$( document ).ready(function() {
$('.start-button').on('click', function() {
$(this).toggle();
countdown();
triviaQuestions();
});
});
Thanks

Your points() function could look something like this:
function points() {
var correct = 0;
$(".choices").each(function(i){
var questionid = $(this).attr('id').split('-')[1];
var answer = $(this).find("input:checked").val();
if (answer == trivia[questionid].answer) correct += 1;
});
$(".points-container").toggle();
$(".points-container span").text(correct);
}
assuming you have an element somewhere on your page like this:
<div class="points-container" style="display:none">Total Points: <span></span></div>
and assuming you add the id="" attibute to your form elements:
$('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + "' id='choices-" + i + "'>");
The function above loops through each form on your page, pulls the question's index in the trivia array from the form's id, and matches the answer given against the answer specified in that index. Perhaps not the most elegant solution, but it worked for me, with minimal edits to your code.

There's a bit going on here so I've given you a complete solution - this covers the timer, the printing of the question/answer sets and the testing functionality.
A complete codepen here: https://codepen.io/V3Dev/pen/vYBaEVL
Details below - enjoy :)
HTML
<input id="trigger" type="button" value="Start Timer" onclick="startTimer();"/>
<p id="timer">60 Seconds Remaining</p>
<br>
<input id="trigger" type="button" value="Test Answers Immediately" onclick="testAnswers();"/>
<br><br><br>
<div id="container"/>
Script
//starting JSON
let trivia = [*JSON*];
//iterate over your JSON
for (let i = 0; i < trivia.length; i++) {
//print the question
document.getElementById("container").appendChild(document.createTextNode(trivia[i].question));
document.getElementById("container").appendChild(document.createElement("br"));
//iterate over the choices and create answer objects
for (let i2 = 0; i2 < trivia[i].choices.length; i2++) {
//print the choices
var input = document.createElement("input");
input.type = "radio";
input.value = trivia[i].choices[i2];
input.name = trivia[i].question;
document.getElementById("container").appendChild(input);
document.getElementById("container").appendChild(document.createTextNode(trivia[i].choices[i2]));
document.getElementById("container").appendChild(document.createElement("br"));
};
//seperate questions
document.getElementById("container").appendChild(document.createElement("br"));
document.getElementById("container").appendChild(document.createElement("br"));
};
//test the submitted answer against the stored value
function testAnswers(){
let score = 0;
for (let i = 0; i < trivia.length; i++) {
let questionSelectedAnswer = getRadioValue(trivia[i].question);
if (questionSelectedAnswer == trivia[i].answer){
score++;
}
}
alert("You scored " + score + "/" + trivia.length);
}
//get the selected value for a collection of answers
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
//set the timer logic
var timer;
function startTimer() {
//clear any running timers
clearInterval(timer);
var secondsRemaining = 60;
timer = setInterval(function() {
secondsRemaining--;
// If the count down is over run the test
if (secondsRemaining < 1) {
clearInterval(timer);
testAnswers();
secondsRemaining = 0;
}
//print the time
document.getElementById("timer").innerHTML = secondsRemaining + " seconds remaining";
}, 1000);
}

Related

javascript matching an item to the correct answer(correct city to country)

making a simple game using javascript, once the start button is selected a country will appear and three cities. One of the three cities matches the country and the other two are false. For example, Ireland will appear and London, Paris, Dublin. The player has to select the correct city to match the country, once they select a city a pop up box will appear saying if they won or lost, if the won, they go onto the next round where another country will appear..
this is the code i have at the moment, there is bits missing, i just don't know where to go from here?
any help is much appreciated, thanks
//all my countries
var countries = ["england", "france", "germany", "hungary", "ireland", `"italy"`, "norway", "spain", "wales"]
//gets the screen height and width for the game
var scnWid,scnHei;
if (self.innerHeight) // works for all except Internet Explorer
{
scnWid = self.innerWidth;
scnHei = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// internet explorer 6 fix
{
scnWid = document.documentElement.clientWidth;
scnHei = document.documentElement.clientHeight;
}
else if (document.body) // Other versions of ie
{
scnWid = document.body.clientWidth;
scnHei = document.body.clientHeight;
}
//shuffles the country array
function shuffleArray(arr) {
var currentIndex = arr.length, temporaryValue, randomIndex ;
//array hasnt stopped
while (0 !== currentIndex)
//find a random element
randomIndex =Math.floor(Math.random() * currentIndex);
//swap it with current element
temporaryValue = arr[currentIndex];
arr[currentIndex] = arr[randomIndex];
arr[randomIndex] = temporaryValue;
//returns the shuffle array
return arr;
}
//variables for the functionality of the game
var randomCountry;
var score;
var count;
var cityClicked;
var winningscore;
//will be passed when the function is called
function gameInit(){
//calculate the number of correct
winningscore = Math.round(3*2)
//the score variable
score = 0;
//is the city clicked yes or no
cityClicked = false;
var gameCountries = [];
var gameCountryCities =[];
//shuffles the existing countries array
gameCountries = shuffleArray(countries)
//loops throught the countries and attached names
for (i = 0; i<gameCountries.length; i++)
{
document.getElementById('gameCountry').innerHTML += "div class='countryName' id= '" + gameCountries[i] + "' onclick='CountryClick'(this.id)'><img src='countries/" + gameCountries[i] + ".gif'></div>" ;}
}
//reshufflies the cities
gameCountryCities = shuffleArray(gameCountries)
//loops through the countries and displays the attached cities
for (j = 0; j<gameCountryCities.length; j++ )
{ document.getElementById('gameCity').innerHTML += "<div class='countrycity' id='country-" + gameCountryCities[j] + "' onclick='cityClick(this.id)'><img src= 'cities/" + gameCountryCities[j] + ".gif'></div>" ;
}
}
//when a city is clicked
function cityClick(cityClickedId)
{
if (cityClicked == true)
{
//does the city and country match
if "country-" + selectedCity == cityClickedId)
{
//add one to the the score
score = score +1;
//show the pop up and score
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.top = scnHei+150;
//GAME
//if the score is less than the winning score the player loses
if (score <winningscore){
gameMessage = "You Lose"
}
//otherwise they win
else {gameMessage = "You Win"}
//Show the game over pop up within the score
document.getElementById("popupBox").innerHTML =
"<div>Game Over</div<div>" + gameMessage +
"</div><div>Your Score is : " + score
+ "</div>";
//show the game over pop up with the score
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//After 5 seconds redirect the user to the level select menu
setTimeout(function(){
window.location = "level.html";
}, 5000);
}
make an object out of the country with the correct city`s in them:
var country = {
"Netherlands": {
capital: "Amsterdam"
},
"Belgium": {
capital: "Brussel"
}
};
country["Belgium"].capital //returns brussel
Check if the result is the same as the given answer and return true or false based on that
var capitals = ['Amsterdam', 'Brussel', 'Barcelona', 'Berlin', 'Rome'];
var generateQuestion = function(country) {
var question = {
1: capitals[Randomizer(1, 5),
2: capitals[Randomizer(1, 5),
3: country[country].capital
}
return question
}
var Randomizer = function(min, max) {
return Math.random() * (max - min) + min;
}
Now you only need to randomize the ID`s for your question and build it from there

Comparring Arrays with For Loops

Alright so I have been working on this one for a bit. I'm comparing the values of two arrays using a For Loop. Every time the array known as cart hits a number that can be found in the products array, it displays the info of the products array, for each time it is hit. I think my code itself is fine ( though I could be wrong) but it's not displaying the values. So I think there's something wrong with my execution of said process there. The codes as follows
function Fill(){
var txt=""
var products = new Array();
products[0] = {name: "refrigerator" , price:88.99, img:"img/refrigerator.jpg"};
products[1] = {name: "microwave oven" , price: 76.99 , img:"img/microwave.jpg"};
products[2] = {name: "dishwasher" , price:276.67 , img:"img/dishwasher.jpg"};
var carts = new Array ();
carts[0]= 2;
carts[1]= 0;
carts[2]= 1;
carts[3]= 1;
carts[4]= 0;
carts[5]= 1;
carts[6]= 2;
carts[7]= 2;
for(var i=0; i < carts.length; i++){
for(var j = 0; j < products.length; j++){
if(carts[i] == j){
txt +=products[j].name + ' ' + products[j].price +" <img src='"+ products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
}
Update answer with ES6:
const products=[{name:"refrigerator",price:88.99,img:"img/refrigerator.jpg"},{name:"microwave oven",price:76.99,img:"img/microwave.jpg"},{name:"dishwasher",price:276.67,img:"img/dishwasher.jpg"}];
const carts=[2,0,1,1,0,1,2,2];
const productsInCart = [...new Set(carts)]
.reduce((a,c)=>{
a.set(c,products[c])
return a;
}, new Map());
const res = carts.map(c=>{
const {name, price, img} = productsInCart.get(c)
return `${name} ${price} <img src="${img}"/>`;
}).join("");
document.body.innerHTML = res;
You should be comparing carts[i] with j otherwise you won't find anything
var txt = ""
var products = new Array();
products[0] = {
name: "refrigerator",
price: 88.99,
img: "img/refrigerator.jpg"
};
products[1] = {
name: "microwave oven",
price: 76.99,
img: "img/microwave.jpg"
};
products[2] = {
name: "dishwasher",
price: 276.67,
img: "img/dishwasher.jpg"
};
var carts = new Array();
carts[0] = 2;
carts[1] = 0;
carts[2] = 1;
carts[3] = 1;
carts[4] = 0;
carts[5] = 1;
carts[6] = 2;
carts[7] = 2;
for (var i = 0; i < carts.length; i++) {
for (var j = 0; j < products.length; j++) {
if (carts[i] == j) {
txt = products[j].name + ' ' + products[j].price + " <img src='" + products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
<div id="answer"></div>
Your txt variable should be modified with = and not +=
You should optimize your code. document.getElementById("answer") could be initiated globally for example.
"carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
What's the value of your appliance variable?
It'll cause the code to error out.
To also steal Alex's answer: "carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
Perhaps this is better?..
carts[7]= 2;
for(var i=0; i < carts.length; i++){
txt +=products[carts[i]].name + ' ' + products[carts[i]].price +" <img src='"+ products[carts[i]].img + "'>"
document.getElementById("answer").innerHTML += txt
}
Upvoting Grimbode's answer as it's pretty close to mine, but cleaner.
I'm not sure why you need the second for loop. You're trying to compare a number with a product object by doing this and it will never work. OK, assuming that what you are trying to achieve is that if carts[0]=2 you want the info for products[2] then try something like:
for(i=0; i<carts.length; i++) {
if(i<products.length) {
currProd=products[carts[i]];
//Process the currProd object as you will
}
}

Is it possible to add weight to images in a generator?

I wish to make a random image generator (which is working fine), however, I was wondering is there a way to add weight to certain images which won't appear as much as others?
I have attached the code below:
<script language="JavaScript">
function random_imglink(){
var myimages=new Array()
myimages[1]="Blue_Car.png"
myimages[2]="Red_Car.png"
myimages[3]="White_Car.png"
myimages[4]="Black_Car.png"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
function confirmRefresh() {
var okToRefresh = confirm("Do you really want to refresh the page?");
if (okToRefresh)
{
setTimeout("location.reload(true);",10);
}
}
</script>
<input type="button" value="Generate a new player" onClick="document.location.reload(true)">
</script>
</a></p>
I do have a SMALL amount of knowledge regarding JavaScript, however, I'm no pro.
var myimages=new Array();
myimages[0]="Blue_Car.png";
myimages[1]="Red_Car.png";
myimages[2]="White_Car.png";
myimages[3]="Black_Car.png";
// myimages[4] = ...
// All values summed up must equal 1
var probabilities=new Array();
probabilities[0]=0.1; // 10%
probabilities[1]=0.1; // 10%
probabilities[2]=0.25; // 25%
probabilities[3]=0.55; // 55%
// probabilities[4] = ... (also need to change the other probability values)
function getImage() {
var rand = Math.random();
var probabilitiy_sum = 0;
for(var i=0; i < probabilities.length; i++) {
probabilitiy_sum += probabilities[i];
if(rand <= probabilitiy_sum ) {
return myimages[i];
}
}
return myimages[myimages.length];
}
// Just for testing:
for(var i=0; i < 10; i++) {
document.getElementById("textbox").innerHTML += getImage() + "<br />";
}
<div id="textbox"></div>
To extend #ByteHamster's response (accept his, not mine), you can do the same thing with an array of objects to easier keep track of the possibilities.
var myimages = [{
image: "Blue_Car.png",
probability: 0.1
}, {
image: "Red_Car.png",
probability: 0.1
}, {
image: "White_Car.png",
probability: 0.25
}, {
image: "Black_Car.png",
probability: 0.55
}];
function getImage() {
var rand = Math.random();
var probabilitiy_sum = 0;
for (var i = 0; i < myimages.length; i++) {
probabilitiy_sum += myimages[i].probability;
if (rand <= probabilitiy_sum) {
return myimages[i].image;
}
}
return myimages[myimages.length].image;
}
// Just for testing:
for (var i = 0; i < 10; i++) {
document.getElementById("textbox").innerHTML += getImage() + "<br />";
}
<div id="textbox"></div>
Easy way would just to be to increase the length of your array, and then add the images with more probability to hit more times, and the images with less probability less times. You can use a for loop for each.
for (i=0;i<15;i++) {
myimages[i] = "Blue_Car.png";
}
for (i=15;i<40;i++) {
myimages[i] = "Red_Car.png";
}
for (i=40;i<80;i++) {
myimages[i] = "White_Car.png";
}
for (i=80;i<100;i++) {
myimages[i] = "Black_Car.png";
}
You already have an answer, but I'll post mine anyway.
<script language="JavaScript">
var counter = 0; // this is just to show that something happens when you randomly get the same car as the previous car.
function random_imglink() {
var myimages = [
{weight: 3, url: "http://insideevs.com/wp-content/uploads/2012/07/bollare-bluecar.jpg"}, // blue
{weight: 10, url: "http://4.bp.blogspot.com/-UKeEILt_8nw/UZOCIEMrMVI/AAAAAAAAAvI/X5i-HaJRnTc/s400/red+car10.jpg"}, // red
{weight: 5, url: "http://i.telegraph.co.uk/multimedia/archive/02661/Audi-A5-Sportback_2661284b.jpg"}, // white
{weight: 2, url: "http://1.bp.blogspot.com/-mojnxHJlWVA/UZ1KShiKMeI/AAAAAAAAHMo/oO7qMo7PJq4/s400/Best-Black-Car-2009_j2bq.gif"} // black
];
// calculate total weigt
// this example: totalWeight = 20
// Then we search a random number from 0 to 19. 0,1,2 belongs to blue; 3 to 12 is red; 13 to 17 is white; 18 to 19 is black
// we add min and max range to the image object, so we can easily return the good one.
var totalWeight = 0;
for (var i=0; i<myimages.length; i++) {
myimages[i].min = totalWeight;
myimages[i].max = totalWeight + myimages[i].weight - 1; // example: if the first weight is 3; the max is 3-1 = 2
totalWeight += myimages[i].weight;
}
var ry = Math.floor(Math.random() * totalWeight);
for (var i=0; i<myimages.length; i++) {
if (ry >= myimages[i].min && ry <= myimages[i].max) {
var index = i; // we've got a winner
break;
}
}
document.getElementById('image').innerHTML = '<img src="' + myimages[index].url + '">';
document.getElementById('counter').innerHTML = counter++;
}
window.onload = function() {
random_imglink();
}
</script>
<input type="button" value="New random car" onClick="random_imglink()">
<div id="counter"></div>
<div id="image"></div>

Can't get my Quiz app to work

I'm doing the "Learn JavaScript Properly" track on http://javascriptissexy.com/how-to-learn-javascript-properly/.
It took me forever, but I finally figured out how to get to the next question, but the choices don't change.
However, when I hard code the "questionIndex" the question and choices work fine.
Anyway here's my code (I know it's a bit messy, I'm a beginner):
http://jsfiddle.net/utfwae8d/1/
HTML:
<div id="container">
<div id="quiz"></div>
<div id="choices"></div>
<input type="button" value="Next">
</div>
JavaScript:
var allQuestions = [{
question: "Who is the best in the world?",
choices: ["CM Punk", "John Cena", "Daniel Bryan", "Roman Reigns"],
correctAnswer: 0
},
{
question: "Who is the current WWE World Champion?",
choices: ["John Cena", "Brock Lesnar", "Triple H"],
correctAnswer: 1
},
{
question: "Where is Toronto located?",
choices: ["Ontario", "California", "Georgia", "Texas"],
correctAnswer: 0
},
{
question: "What is the largest California city?",
choices: ["Los Angeles", "San Fransico", "San Deigo", "Anahiem"],
correctAnswer: 0
}];
var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.querySelector('[type=button]');
var correctAnswers = 0;
var questionIndex = 0;
function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
var choicesNum = allQuestions[questionIndex].choices.length;
var correctAnswer = allQuestions[questionIndex].correctAnswer;
var choices;
for (var i = 0; i < choicesNum; i++) {
choices = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choices + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
nextButton.addEventListener('click', function () {
questionIndex++;
quiz.textContent = allQuestions[questionIndex].question;
});
}
showQuiz();
The button's click handler is not updating the answers, it's only updating the question.
I've separated the code into two functions: one that shows the quiz, and one that shows the answers.
var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.querySelector('[type=button]');
var questionIndex = 0;
function showAnswers() {
choicesContainer.innerHTML = "";
var choicesNum = allQuestions[questionIndex].choices.length;
for (var i = 0; i < choicesNum; i++) {
var choice = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choice + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}
function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
}
showQuiz();
showAnswers();
nextButton.addEventListener('click', function () {
questionIndex++;
showQuiz();
showAnswers();
});
Your issue is in the eventlistener method. I have modified your code as below and it works.
nextButton.addEventListener('click', function () {
var newChoicesHTML="";
var newChoices;
questionIndex++;
choicesNum = allQuestions[questionIndex].choices.length;
quiz.textContent = allQuestions[questionIndex].question;
for (var i = 0; i < choicesNum; i++) {
newChoices = allQuestions[questionIndex].choices[i];
newChoicesHTML+= "<input type='radio' name='choice'>" + newChoices + "</input></br>";
}
choicesContainer.innerHTML = newChoicesHTML;
});
Basically the issue is on event change you are updating your question but not the answers.
Your showQuiz function is doing 3 things:
setting the question text
setting the answer list
adding an event listener to the button
When the button is clicked, your code updates the question text but doesn't update the answer list. So I pulled adding the event listener out (it only needs to be executed once) and then made the button click call showQuiz again. Also I added a line to blank out the previous choices.
function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
var choicesNum = allQuestions[questionIndex].choices.length;
var correctAnswer = allQuestions[questionIndex].correctAnswer;
var choices;
choicesContainer.innerHTML = '';
for (var i = 0; i < choicesNum; i++) {
choices = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choices + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}
nextButton.addEventListener('click', function () {
questionIndex++;
showQuiz();
});

How to get number of option is answered/not answered using jQuery?

In android phonegap application, I created 5 or more question with respective option (checkboxes) in div dynamically. Each question and respective option have same id. Now I want to know how many question are answered/how many questions are not answered while clicking submit button.
please guide me. Thanks in advance.
My code is:
for dynamic div: retrive value from local database
function list(results){
for (i = 0; i < results.rows.length; i++) {
$("#poll").append("<li id='"+i+"'>"+results.rows.item(i).ques+"</li>"+"<br/>" );
var optiontypearray = new Array();
var arr = results.rows.item(i).option;
var optiontypearray=arr.split(" ");
for(var j=0; j<optiontypearray.length; j++) {
$("#poll").append("<input id='"+i+"' name='ckbox' value='"+optiontypearray[j]+"' type='checkbox'/>"+optiontypearray[j]+"<br/>");
}
}
}
for submit button:get question with respective answer
function submit(){
$answers = $(':checked');
var $questions=$('li');
$answers.each(function(index,el) {
var list1=$(this).attr("id");
alert("list1:"+list1);
var val=$('#'+list1).val();
alert($questions.eq(list1).html() + ' : ' + $(el).val());
});
}
HTML:
<div id="poll">
This is what happens when you click submit button.
$('#submit').click(function () {
var questionsAnswered = questionsNotAnswered = 0
var arrQuestions = new Array();
$('li').removeAttr('style').each (function (i) {
if ($(this).children('input:checked').length > 0) {
var ans = '';
$(this).children('input:checked').each(function () {
ans+= $(this).val() + ', ';
});
arrQuestions[questionsAnswered] = new Array($(this).attr('id'), ans);
questionsAnswered++;
} else if ($(this).attr('class') == 'required' && $(this).children('input:checked').length == 0) {
$(this).css({border : '1px solid red'});
questionsNotAnswered++;
alert($(this).clone().children('span').remove().end().text());
}
});
$('div#finalResults').html("Questions Answered : " + questionsAnswered + "<br /> Questions Not Answered : " + questionsNotAnswered);
});
$.each (arrQuestions, function () {
$('div#finalResults').append("<br /> Q: " + this[0] + " A: " + this[1]);
});
Demo. http://jsfiddle.net/tmM76/9/
Please note that the code in list() function might change as per your existing code which you did not share ;-).
u can do something like..
var qanswered;
for( j = 0; j < numberofQuestions; j++){
qanswered = false;
ques = questions[j];
for( k = 0; k < ques.choices.length; k++){
btn = $('.ui-page-active input#'+k); // k is your choice id whatever way u define it
if(btn[0].checked){
qanswered = true;
}
}
if(!qanswered){
//this question is not answered, do something
}
}
btn gets the jquery object of the inputs one by one, of the ques

Categories

Resources