array of object containg multiple array of element in "JAVASCRIPT" - javascript

I am trying to create object for given set of Question
Each question contain set of answers which mat vary from minimum : 1 to maximum: 5.
HTML
<div id="displayAppendedQuestion" style="display: block;">
<div id="questionNumber1">
Question1 = Foo - 1 <br>
<input id="radioVal1.1" name="radioinput" type="radio" value="Answer 1.1 "> Answer 1.1 <br>
<input id="radioVal1.2" name="radioinput" type="radio" value="Answer 1.2"> Answer 1.2 <br>
<input id="radioVal1.3" name="radioinput" type="radio" value="Answer 1.3"> Answer 1.3 <br>
<input id="radioVal1.4" name="radioinput" type="radio" value="Answer 1.4"> Answer 1.4 <br>
<input id="radioVal1.5" name="radioinput" type="radio" value="Answer 1.5"> Answer 1.5 <br>
</div>
<div id="questionNumber2">
Question2 = Foo - 2 <br>
<input id="checkboxVal2.1" name="checkBoxInput" type="checkbox" value="Answer 2.1"> Answer 2.1 <br>
<input id="checkboxVal2.2" name="checkBoxInput" type="checkbox" value="Answer 2.2"> Answer 2.2 <br>
<input id="checkboxVal2.3" name="checkBoxInput" type="checkbox" value="Answer 2.3"> Answer 2.3 <br>
<input id="checkboxVal2.4" name="checkBoxInput" type="checkbox" value="Answer 2.4"> Answer 2.4 <br>
<input id="checkboxVal2.5" name="checkBoxInput" type="checkbox" value="Answer 2.5"> Answer 2.5 <br>
</div>
<div id="questionNumber3">
Question3 = Foo - 3 <br>
<input id="inputVal3" type="text" readonly="readonly" value="Answer 3.1"> <br>
</div>
<div id="questionNumber4">
Question2 = Foo - 4 <br>
<input id="checkboxVal4.1" name="checkBoxInput" type="checkbox" value="Answer 4.1"> Answer 4.1 <br>
<input id="checkboxVal4.2" name="checkBoxInput" type="checkbox" value="Answer 4.2"> Answer 4.2 <br>
<input id="checkboxVal4.3" name="checkBoxInput" type="checkbox" value="Answer 4.3"> Answer 4.3 <br>
<input id="checkboxVal4.4" name="checkBoxInput" type="checkbox" value="Answer 4.4"> Answer 4.4 <br>
<input id="checkboxVal4.5" name="checkBoxInput" type="checkbox" value="Answer 4.5"> Answer 4.5 <br>
</div>
</div>
Question:
How to create object for given set of input using javascript.
JavaSript
I have no of total Questions = totalQuestions
// create object for
for ( var i = 1 ; i < totalQuestions ; i++){
inputs = document.getElementById('questionNumber'+i).getElementsByTagName('input');
var obj = {
question: ("QUESTION_" + document.getElementById('Ques').value),
answertype: ("QTYPE_" + document.getElementById('surAnsType').value)
for (var j = 0, l = inputs.length; j < l; ++j) {
if (inputs[j].value.length) {
options:option_arr.push(inputs[j].value);
}
}
};
arrayOfObject.push(obj);
}

You can't put a for loop inside an object literal.
for ( var i = 1 ; i <= totalQuestions ; i++){
inputs = document.getElementById('questionNumber'+i).getElementsByTagName('input');
var option_arr = [];
for (var j = 0, l = inputs.length; j < l; ++j) {
if (inputs[j].value.length) {
option_arr.push(inputs[j].value);
}
}
var obj = {
question: ("QUESTION_" + document.getElementById('Ques').value),
answertype: ("QTYPE_" + document.getElementById('surAnsType').value),
options: option_arr
};
arrayOfObject.push(obj);
}
Since your question numbers run from 1 to totalQuestions, the for test should use <=, not <.

Assuming the JSON format,
obj = {
question_no: 1,
question: "Foo 1",
answers: [{
answer_no: 1,
answer: "Answer 1"
},
{
answer_no: 1,
answer: "Answer 1"
},
//.....
]
}
There will be a few modifications in your HTML.
<div id="questionNumber1" class="ques">
<span class="question">Question1 = Foo - 1</span><br/>
<input id="radioVal1.1" name="radioinput" type="radio" value="Answer 1.1">Answer 1.1<br>
<input id="radioVal1.2" name="radioinput" type="radio" value="Answer 1.2">Answer 1.2<br>
<input id="radioVal1.3" name="radioinput" type="radio" value="Answer 1.3">Answer 1.3<br>
<input id="radioVal1.4" name="radioinput" type="radio" value="Answer 1.4">Answer 1.4<br>
</div>
Your javascript code will be,
$('.ques').each(function(qindex) {
var obj = {
question_no: qindex+1,
question: $(this).find('.question').text(),
answers: new Array()
};
$(this).find('input[type="radio"]').each(function(index) {
obj.answers.push({
answer_no: index + 1,
answer: $(this).val()
});
});
arrayOfObj.push(obj);
});

Related

How do I check two options at once in the option quiz?

I did it as you wanted and it still doesn't work as it should, if I don't check anything in the checkbox and give it an "evaluate test" so it will write me 1 point anyway, which is wrong. Some ideas?
function check(){
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelectorAll('input[value="question2"]:checked', 'input[value="question2"]:checked');
var correct = 0;
if (question1 !=null && question1.value == " Červená, Zelená, Modrá") {
correct++;
}
if (question4 !=null &&question4.value == "Rastrová grafika","Vektorová grafika"){
correct++;
}
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
<form class="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value=" Červená, Zelená, Modrá"> Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value=" Červená, Zelená, Žlutá"> Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value=" Černá, Fialová, Modrá"> Červená, Fialová, Modrá<br>
</form>
<form class="quiz">
<p style="font-weight: 900">Způsoby jakým počítače ukládají a zpracovávají obrazové informace se nazývají? (Vyber dvě možnosti)</p>
<input type="checkbox" class='question2' name="question4" value=" 3D grafika"> 3D grafika<br>
<input type="checkbox" class='question2' name="question4" value=" Vektorová grafika"> Vektorová grafika<br>
<input type="checkbox" class='question2' name="question4" value=" Fotografika"> Fotografika<br>
<input type="checkbox" class='question2' name="question4" value=" Rastrová grafika"> Rastrová grafika<br>
</form>
<br>
<div id="number_correct"></div>
question2 needs to be the result of a call to querySelectorAll, not just querySelector. It will then be a list of all the checked elements (querySelector only returns the first matched element, no matter how many match the selector.
You would need to loop the list and see what it contains. You need to verify that only two boxes were checked, and that they were the correct ones.
Also in your code, the question4 variable isn't defined, and input[value="question2"]:checked will never match anything - there's no checkbox with that value, and looking for the value makes no sense anyway. Also your question2 checkboxes randomly had "question4" as their name. I've corrected those issues and a couple of other minor things.
Something like this will work better:
function check() {
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelectorAll('input[name="question2"]:checked');
var correct = 0;
if (question1 != null && question1.value == "Červená, Zelená, Modrá") {
correct++;
}
var q2answers = ["Rastrová grafika", "Vektorová grafika"];
var correctQ2NumAnswers = (q2answers.length == question2.length);
var correctQ2AnswersCount = 0;
question2.forEach(function(el) {
if (q2answers.includes(el.value)) correctQ2AnswersCount++;;
});
if (correctQ2NumAnswers == true && correctQ2AnswersCount == q2answers.length) correct++;
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
document.querySelector("#check").addEventListener("click", check);
<form class="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Modrá"> Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Žlutá"> Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value="Černá, Fialová, Modrá"> Červená, Fialová, Modrá<br>
</form>
<form class="quiz">
<p style="font-weight: 900">Způsoby jakým počítače ukládají a zpracovávají obrazové informace se nazývají? (Vyber dvě možnosti)</p>
<input type="checkbox" class='question2' name="question2" value="3D grafika"> 3D grafika<br>
<input type="checkbox" class='question2' name="question2" value="Vektorová grafika"> Vektorová grafika<br>
<input type="checkbox" class='question2' name="question2" value="Fotografika"> Fotografika<br>
<input type="checkbox" class='question2' name="question2" value="Rastrová grafika"> Rastrová grafika<br>
</form>
<br>
<div id="number_correct"></div>
<button type="button" id="check">
Check Answers
</button>

get all elements by class name of text boxes in javascript

I have a few text boxes on my javascript page with the class of textID. So if I were to do
function UpdateTotals() {
getText = document.getElementsByClassName('textID').value;
}
All of the values will be numbers, so how do I add all of the values in this class together? Example: there are 4 text boxes, each one has the number 2 in it. I want to get 8 by adding them all together (but only the text boxes that are in that class).
One example could be using Array.prototype.reduce()
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.textContent.trim()), 0);
console.log(total); // 8
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
For INPUT elements:
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.value), 0);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Using NodeList.forEach()
const textID = document.querySelectorAll('.textID');
let total = 0;
textID.forEach(el => total += +el.value);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Try this code:
HTML code:
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<br><br>
Total : <input type="text" name="total" id="total"/>
Sum
JS code:
window.sumInputs = function() {
var inputs = document.getElementsByClassName('textID'),
result = document.getElementById('total'),
checkboxes = document.querySelectorAll(`input[name="qty"]:checked`),
sum = 0;
for(var i=0; i<checkboxes.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
Try it in jsfiddle : https://jsfiddle.net/u62tyj45/

Quiz percentage validation IF - THEN functions

I am working to create a quiz. and I want to add the option for all the people that has 60% or more to have a congratilation message and to show a link to another web page were they can go and fill a form. For 60% or less just to show a sorry message.
Below is my sample code for my quiz. (this has only 2 questions FYI)
Thanks :
var numQues = 2;
var numChoi = 3;
var answers = new Array(2);
answers[0] = "Answer 1-1";
answers[1] = "Answer 2-1";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
<form name="quiz">
1. Question 1<br>
<input type="radio" name="q1" value="Answer 1-1">Answer 1-1<br>
<input type="radio" name="q1" value="Answer 1-2">Answer 1-2<br>
<input type="radio" name="q1" value="Answer 1-3">Answer 1-3<br>
<p>
2. Question 2<br>
<input type="radio" name="q2" value="Answer 2-1">Answer 2-1<br>
<input type="radio" name="q2" value="Answer 2-2">Answer 2-2<br>
<input type="radio" name="q2" value="Answer 2-3">Answer 2-3<br>
<p>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear"><p>
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea>
</form>

Javascript help, randomizing quiz questions

i made some code recently but im wondering how to make the quiz choose 3 questions out of 6 instead of displaying 6 straight away. Help would be appreciated. I want the quiz to choose 3 questions at random, then if its reloaded have a chance to choose another 3 questions, out of a total pool of 6.
<script language="JavaScript">
var numQues = 6;
var numChoi = 3;
var answers = new Array(6);
answers[0] = "16";
answers[1] = "8";
answers[2] = "The Walking Dead";
answers[3] = "Batman v Superman";
answers[4] = "Tupac";
answers[5] = "#ATAME2016";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
</script>
</head>
<body>
<form name="quiz">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
<p>
2. How many pages are on this website?<br>
<input type="checkbox" name="q2" value="8">8<br>
<input type="checkbox" name="q2" value="6">6<br>
<input type="checkbox" name="q2" value="7">7<br>
<p>
3. What's the most popular show this week?<br>
<input type="checkbox" name="q3" value="The Walking Dead">The Walking Dead<br>
<input type="checkbox" name="q3" value="Mandem on the wall">Mandem on the wall<br>
<input type="checkbox" name="q3" value="Cotchin with Ksara">Cotchin with Ksara<br>
<p>
4. What movie has made the most money this week in the box office?<br>
<input type="checkbox" name="q4" value="Ride along 2">Ride along 2<br>
<input type="checkbox" name="q4" value="Batman v Superman">Batman v Superman<br>
<input type="checkbox" name="q4" value="GasMan">GasMan<br>
<p>
5. Which star in the celebrity page is no longer alive?<br>
<input type="checkbox" name="q5" value="Tupac">Tupac<br>
<input type="checkbox" name="q5" value="50 Cent">50 Cent<br>
<input type="checkbox" name="q5" value="Bradley cooper">Bradley cooper<br>
<p>
6. What is our twitter account name (#)?<br>
<input type="checkbox" name="q6" value="#ATAME">#ATAME<br>
<input type="checkbox" name="q6" value="#ATAME2016">#ATAME2016<br>
<input type="checkbox" name="q6" value="#A2THETAME">#A2THETAME<br>
<p>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear"><p>
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea>
</form>
</div>
You'll want to use a Math.random() function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
A common example is found at: http://www.w3schools.com/jsref/jsref_random.asp
I'd try something like this, using jQuery:
// Hides all questions on page load.
$('.questions').hide();
// Randomly shows 3 questions.
for (var i=0; i<3; i++) {
var questionId = Math.floor((Math.random() * 6) + 1);
$('#question-' + questionId).show();
}
Then wrap your questions in wrapping <div> or <p> tags like this:
<div id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</div>
Or this:
<p id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</p>

Quiz - Counts Radio Button Values

I'm trying to create a Quiz for a Spanish class. I have little experience with JavaScript, but am fairly proficient with html and CSS. I have a question and followed by three radio buttons with answers. There are two incorrect answers and a correct answer. I have 45 questions total.
<form name="quiz" method="post" name="buttons" id="form" onsubmit="return totalVal()">
<li><div class="question">¿Quién detestan la nueva casa?</div></li>
<input id="answer" type="radio" name="group1" value="wrong"> Josh<br>
<input id="answer" type="radio" name="group1" value="wrong"> Amanda<br>
<input id="answer" type="radio" name="group1" value="correct"> Josh y Amanda<hr>
<li><div class="question">¿Quién es señor Dawes?</div></li>
<input id="answer" type="radio" name="group2" value="wrong">Un familia amigo<br>
<input id="answer" type="radio" name="group2" value="wrong">Un gato<br>
<input id="answer" type="radio" name="group2" value="correct">Un amable joven de la agencia de bienes raíces<hr>
<li><div class="question">¿Quién qué sus buscan?</div></li>
<input id="answer" type="radio" name="group3" value="wrong">Josh<br>
<input id="answer" type="radio" name="group3" value="wrong"> Petey<br>
<input id="answer" type="radio" name="group3" value="correct" >Josh y Petey<hr>
<button class="submit" onclick="showTotalvalue();" type="submit">Submit</button></div>
I want to use some basic Javascript to count all the "correct" radio button values and output to a new page or alert box that displays after the user clicks submit.
I found this in my research. In my googling, I haven't been able to find a snippet of code that counts the "correct" values. The link above is the closest I've gotten. I attached the JavaScript that I changed to fit my situation from the suggestion on the other post.
totalVal = 0;
// calculate the total number of corrects clicked
for (y = 0; y = incorrectOfQuestion; y++) {
var questionNo = document.getElementsByName("questions" + y);
for (i = 0; i < questionNo.length; i++) {
if (document.myform.questions[i].checked == true) {
totalVal = totalVal + parseInt(document.myform.questions[i].value, 45);
}
}
}
Any assistance is greatly appreciated as I am in a time crunch! Thank you!
This should be the code you require to get it working with an alert box:
function handleClick()
{
var amountCorrect = 0;
for(var i = 1; i <= 45; i++) {
var radios = document.getElementsByName('group'+i);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if(radio.value == "correct" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct Responses: " + amountCorrect);
}
<form name="quiz" method="post" name="buttons" id="quiz" onsubmit="return false">
<li><div class="question">¿Quién detestan la nueva casa?</div></li>
<input id="answer" type="radio" name="group1" value="wrong"> Josh<br>
<input id="answer" type="radio" name="group1" value="wrong"> Amanda<br>
<input id="answer" type="radio" name="group1" value="correct"> Josh y Amanda<hr>
<li><div class="question">¿Quién es señor Dawes?</div></li>
<input id="answer" type="radio" name="group2" value="wrong">Un familia amigo<br>
<input id="answer" type="radio" name="group2" value="wrong">Un gato<br>
<input id="answer" type="radio" name="group2" value="correct">Un amable joven de la agencia de bienes raíces<hr>
<li><div class="question">¿Quién qué sus buscan?</div></li>
<input id="answer" type="radio" name="group3" value="wrong">Josh<br>
<input id="answer" type="radio" name="group3" value="wrong"> Petey<br>
<input id="answer" type="radio" name="group3" value="correct" >Josh y Petey<hr>
<button class="submit" onclick="return handleClick();" type="submit">Submit</button>
</form>
#pimvdb had used the === operator when checking for the "correct" string which does not allow type conversion and was therefore failing. He also used getElementsByClassName but the elements do not have a class applied to them so this was incorrect.
The working version can be found in the fiddle below. As you can see the onsubmit of the form has been set to "return false" to stop the form from posting.
http://jsfiddle.net/g45nG/1/
You can loop over each radio group, then loop over each radio button to check whether the correct one is checked.
var amountCorrect = 0;
for(var i = 1; i <= 45; i++) {
var radios = document.getElementsByName("group" + i);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if(radio.value === "correct" && radio.checked) {
amountCorrect++;
}
}
}

Categories