How can I Iterate through an array of questions and answers - javascript

I am in the process of creating a quiz in javascript; At present I have a forward and back button which iterates through my questions! \0/
Also, I have managed to create some radio buttons and able to extract the first array of answers.
My problem is I can't iterate through the rest of answers (in the array) to match the questions...
This is the html:
<div class="container">
<div class="sixteen columns">
<div class="row"></div>
<h1>
Welcome to the <br>ultimate nerd quiz!
</h1>
<form id="f1" method="post">
<div id="question"></div>
</form>
<button class='navBackward'><</button><button class='navForward'>></button>
</div>
<!-- sixteen columns -->
</div>
<!-- container -->
This is the array:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0},
{
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3}, {}]; //etc
This is my JS: (This is what creates the initial radio buttons and the first set of answers)
function createRadioButtonFromArray(array) {
var len = array.length;
var form = document.getElementById("f1");
for (var i = 0; i < len; i++) {
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
form.appendChild(radio);
form.appendChild(radioText);
}
}
createRadioButtonFromArray(item.choices);
This is what I am trying to use to display the other choices/answers in the array..
function answerFwd(){
var answerOutput = " ";
var itemAnswers = allQuestions;
if(currentAnswer <= itemAnswers.length){
currentAnswer++;
}
I suppose the problem is I am not properly outputting the array contents...
var answerOutput = "<p>" + itemAnswers[currentQuestion].choices + "</p> <br/>";
update = document.getElementById("f1");
update.innerHTML = answerOutput;
}

I guess you should do something like that instead :
HTML : (-> add a responses' div, like the question's one)
<div class="container">
<div class="sixteen columns">
<div class="row"></div>
<h1>
Welcome to the <br>ultimate nerd quiz!
</h1>
<form id="f1" method="post">
<div id="question"></div>
<div id="responses"></div>
</form>
<button class='navBackward'>
<</button>
<button class='navForward'>></button>
</div>
<!-- sixteen columns -->
</div>
JS :
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses"); // <- reach the responses div instead of the form
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
// ...
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices); // <- Why don't you use the function you created earlier ????
/*
var answerOutput = "<p>" + itemAnswers[currentQuestion].choices + "</p> <br/>";
update = document.getElementById("f1");
update.innerHTML = answerOutput;
*/
}
See the jsFiddle : http://fiddle.jshell.net/msieurtoph/uD29v/
(I did not implement the 'backward answers' function)

I suppose the problem is I am not properly outputting the array
contents...
Yes. Your contents is an array, so you would need to iterate it
var answerOutput = "<p>" + itemAnswers[currentQuestion].choices[0] + "</p> <br/>";
JSFiddle demo on how to iterate the array

Related

How to debug\compile\find errors in my JavaScript Code in 'script.js' file, in VS Code?

I am starting with web Development. I know basics of HTML and JavaScript.I'm working with VS Code. The problem I'm facing is that I cannot identify errors in my JavaScript code which i wrote in the 'script.js' file. The errors range from missing a semicolon to other conceptual errors.
The only solution that worked for me so far was running the code in an external JavaScript compiler such as on https://js.do/ .Every time I copy-paste the code to check for errors.
I tried to search for VS Code Extensions. I came across 'Debugger for Chrome' and 'Linters'. I tried installing them, but they didn't make a lot of sense to me. What is the correct way to check for errors and what is 'Debugger' and 'Linter' ?
Below is the code I wrote for SPI(Semester Performance Index) Calculator.
function calculate() {
var arr1 = [];
var arr2 = [];
var totalscore = 0;
for (var i = 1; i <= instance; i++) {
arr1[i] = document.getElementById("GC" + i).value;
arr2[i] = parseInt(document.getElementById("CC" + i).value);
}
for (var i = 1; i < arr1.length; i++) {
totalscore += arr1[i] * arr2[i];
}
var message = "Dear " + document.getElementById("name").value + ",<br>" + "Your SPI is " + Math.round((totalscore / getSum(arr2)) * 100) / 100;
var paraElement = document.createElement("p");
paraElement.innerHTML = message;
paraElement.id = "" + instance;
var con = document.getElementById("result");
con.appendChild(paraElement)
//return false;
}
function getSum(arr) {
var s = 0;
for (var i = 1; i < arr.length; i++)
s += arr[i];
return s;
}
function Initial() {
AddCourse();
AddCourse();
AddCourse();
}
var instance = 0;
function AddCourse() {
instance++;
var details = [
{ GRADE: "A*", GC: 10 },
{ GRADE: "A", GC: 10 },
{ GRADE: "B", GC: 8 },
{ GRADE: "C", GC: 6 },
{ GRADE: "D", GC: 4 },
{ GRADE: "E", GC: 2 },
{ GRADE: "F", GC: 0 }
];
//Creating DropDown List Element
var grade = document.createElement("SELECT");
grade.id = "GC" + instance;
//Adding Options to the Dropdown List
for (var i = 0; i < details.length; i++) {
var option = document.createElement("OPTION");
option.innerHTML = details[i].GRADE;
option.value = details[i].GC;
grade.options.add(option);
}
//Creating number of credits input
var credits = document.createElement("input");
credits.setAttribute("type", "number");
credits.id = "CC" + instance;
credits.value = 0;
//Creating Label elements
var lab = document.createElement("label");
lab.innerHTML = "COURSE " + instance + ":<br>";
var lab2 = document.createElement("label");
lab2.innerHTML = "GRADE: ";
var lab3 = document.createElement("label");
lab3.innerHTML = " CREDITS: "
var lab4 = document.createElement("br");
//Referencing dvContainer
var dvContainer = document.getElementById("dvContainer");
//Adding Dropdown to Container
var div = document.createElement("DIV");
div.appendChild(lab);
div.appendChild(lab2);
div.appendChild(grade);
div.appendChild(lab3);
div.appendChild(credits);
dvContainer.appendChild(div);
dvContainer.appendChild(lab4);
dvContainer.appendChild(lab4);
}
<html>
<head>
<title> SPI Calculator</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="Initial()">
<form name="details">
<div>
<label for="names">Name:</label>
<input type="text" id="name">
</div>
<br>
<b>Enter Expected Grades</b>
<br><br>
<div id="dvContainer"></div>
<input type="button" id="btnAdd" onclick="AddCourse()" value="Add Course" />
<br><br>
<div>
<button type="button" onclick="calculate()">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
<div id="result"></div>
</body>
</html>
The result doesn't show any error, and the code isn't running properly.
I tried removing semicolon from
line 23: con.appendChild(paraElement),
to see if any error arises in VS Code but it was of no help.
Here's an answer to your question :
How to quickly test some javascript code?
Following is a free list of tools you can use to check, test and verify your JS code:
Google Code Playground
JavaScript Sandbox
jsbin
jsfiddle
pastebin
jsdo.it
firebug
html5snippet.net
Hope this helps.
Edit : typo

Storing inputed numerical values with a for loop on JavaScript/HTML

I am new to JavaScript and am trying to program this code for my school. The ultimate goal is to make a final grade calculator where the students input their current grades and the program outputs what they need to score on the final to keep a certain percentage. This program is supposed to be for weighted classes in which the teachers weight different assignments/tests different amounts. The problem is that some teachers use more categories than others which is why there is a for loop. With the following, the user is able to input all the info but I cannot store the extra category weights and grades as a variable so I cant do the math with them. If that made any sense, I would appreciate if you knew how to store the values that are inputed within the for loops.
<html>
<head>
<script type='text/javascript'>
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var weight = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
var percentage = row.children[1].value;
console.log(weight, percentage);
}
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
Just use array in javascript. I have used array and your page is working fine now.
You can check it and Tell if there some problem...
<html>
<head>
<script type='text/javascript'>
var w = [];
var p = [];
var result = 0;
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
w[i] = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
p[i] = row.children[1].value;
}
for(var i =0; i < rows.length; i++){
// You can do as much calculation here with w[i] & p[i]
result += w[i]*p[i];
}
console.log(result);
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
I hope this will solve your problem :)
Didn't quite understand where your problem is. You can store all of your extra weighted categories inside of an array.
for example:
var categories = [];
categories.push(value);
For your issue, value can be a weighted category (weight + percentage).
Your code should be as follows:
<html>
<head>
<script type='text/javascript'>
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
// The categories array initialization
var categories = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var weight = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
var percentage = row.children[1].value;
// Pushing a specific category that contains weight and percentage (Defined by a JSON struction)
categories.push({
weight: weight,
percentage: percentage
});
console.log(weight, percentage);
}
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
Later on your calculations, your can for loop on the categories array and calculate by the categories that you've pushed into the array

Write multiple strings on the same id [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have the input of 'Fred'.
How can I print it so that it looks like this?
Character List:
F
r
e
d
And that it is all being written to a paragraph element in html with the id = 'msg2'
So far all that I can get it to write is either F or d
Apologies, forgot to include code
function start () {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString (pString) {
for (i = 0; i < pString.length; i++) {
t = i + 1
var vReturnName = ('Character list: <br />' + (pString.substring(i, t)))
}
return (vReturnName);
}
Split the string and use forEach to loop over the array then create new element and just put it in the DOM:
let str = "FRED";
str.split('').forEach(s => {
let p = document.createElement('p');
p.textContent = s;
document.body.appendChild(p);
})
p{border-bottom:solid 1px #c8c8c8;}
Your code has few issues:
var vReturnName = inside loop will always have last value as you are overriding it. Move declaration outside loop and the use vReturnName += to append
(pString.substring(i, t)) This will give you single character but you are not adding <br/> after it and so you will have no line-breaks. Also you can use string.charAt instead of it.
for (i = 0; Any variable defined without var|let|const becomes global.
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = 'Character list: <br />'
for (i = 0; i < pString.length; i++) {
t = i + 1
vReturnName += (pString.substring(i, t) + "<br/>")
}
return (vReturnName);
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
Alternate solution:
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = wrapInP('Character list:')
for (var i = 0; i < pString.length; i++) {
vReturnName += wrapInP(pString.charAt(i))
}
return vReturnName;
}
function wrapInP(str){
return "<p>" + str + "</p>"
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
References:
Is it sometimes bad to use <BR />?
string.charAt(x) or string[x]?
Use String#split to get array of each character.
Use Array#join to get the string concatenated with <br><br>
var name = "Fred";
var newName = name.split('').join('<br><br>');
document.getElementById('msg2').innerHTML = newName;
<div id='msg2'></div>
You have to split up the text and append it to the div like so:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
$('#msg2').append(characters[i]+'<br/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = 'msg2'></div>
If using Pure JS:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
document.getElementById('msg2').innerHTML+=characters[i]+'<br/>';
}
<div id = 'msg2'></div>

Generating radio buttons with label

I'm trying to select items from a Select list and generate a Radio list.
Let's say I have these options in a list:
abc
dab
I want to print them in a radio list like this:
(radiobutton1) abc
(radiobutton2) dab
But right now I am just getting a result like this:
(radiobutton1)(radiobutton2) abc dab
Here is my code:
HTML
<radio id = MyRadio multiple></radio>
<label id = MyLabel multiple></label>
and Javascript:
function btn2Click() {
var SelectedItems = document.getElementById("MyList");
var i;
for (i = 0; i < SelectedItems.length; i++)
{
if(SelectedItems.options[i].selected)
{
var RadioSelect = document.createElement("INPUT");
RadioSelect.setAttribute("type", "radio");
var RadioText = document.createTextNode(SelectedItems.options[i].text+'\n');
RadioSelect.appendChild(RadioText);
document.getElementById("MyRadio").appendChild(RadioSelect);
document.getElementById("MyLabel").appendChild(RadioText);
}
}
}
something like this? http://jsfiddle.net/swm53ran/101/
<div class="radioButtons">
Place Radio Buttons Here
<br/>
</div>
$(document).ready(function() {
var list = ['dog', 'cat', 'fish'];
var html = "<input type='radio'/>";
for (var i = 0; i < list.length; i++) {
$('.radioButtons').append(html + list[i] + '<br/>');
}
});
Labels work with the for attribute. The for attribute needs to refer to the id of the radio input.
if(SelectedItems.options[i].selected)
{
var RadioSelect = document.createElement("INPUT");
RadioSelect.setAttribute("type", "radio");
var RadioText = document.createTextNode(SelectedItems.options[i].text+'\n');
document.getElementById("MyRadio").appendChild(RadioSelect);
document.getElementById("MyLabel").appendChild(RadioText);
}
Change the label html to:
<label id="MyLabel" for="MyRadio" multiple></label>
HTML
<div id="myRadioButtons" />
JS
var html='';
$.each(['apply', 'pear', 'peach', 'lime'], function (i, v){
html += "<input type='radio'/>" + v + '<br/>';
});
$('#myRadioButtons').append(html);
DEMO

get html element inside another element in javascript

Hi
I am creating dynamic div elements , let say 4 div are there . div1,div2,div3,div4. each div has set of radio buttons rad1,rad2,rad3,rad4 . see as follows.
div1 ->rad1,rad2,rad3,rad4 groupName=rd1 ->end div1
div2 ->rad1,rad2,rad3,rad4 groupName=rd2 ->end div2
div3 ->rad1,rad2,rad3,rad4 groupName=rd3 ->end div3
div4 ->rad1,rad2,rad3,rad4 groupName=rd4 ->end div4
This is dynamically created html. i want to get which Radio selected from div2 or div3 what script i have to write ?
DEMO: http://so.lucafilosofi.com/get-html-element-inside-another-element-in-javascript
function checkRadio() {
var radios = document.getElementById('rBox').getElementsByTagName('input');
for (var i = 0; i < radios.length; i++) {
radios[i].onclick = function(e) {
var pid = this.parentNode.id;
if ( pid == 'group-2' || pid == 'group-3' )
alert('PARENT: ' + this.parentNode.id )
}
}
}
<body onload="checkRadio()">
<div id="rBox">
<div class="rad" id="group-1">
<input type="radio" name="option" />
....
</div>
<div class="rad" id="group-2">
<input type="radio" name="option" />
....
</div>
....
</div>
</body>
use jquery
use jquery-> $.live()
If I understood you right, this may help you:
var num_of_options = 4;
var selected = new Array();
var op, i, j;
for (j=1;j<=num_of_options;j++) {
op = document.getElementsByName("rd"+j);
for (i in op) {
if (op[i].checked) {
selected[j] = op[i].value;
}
}
}
selected will contain the selected values for the radio groups in each divs.
Here is crude sample code that will show the selected value in each div:
var arrDivs = ["div1", "div2", "div3"];
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = document.getElementById(arrDivs[i]);
if (oDiv) {
var arrInputs = oDiv.getElementsByTagName("input");
var blnFound = false;
for (var j = 0; j < arrInputs.length; j++) {
var oInput = arrInputs[j];
if (oInput.type == "radio" && oInput.checked) {
alert("The value of selected radio in div '" + arrDivs[i] + "' is: " + oInput.value);
blnFound = true;
break;
}
}
if (!blnFound)
alert("div '" + arrDivs[i] + "' contains no selected radio button");
}
else {
alert("div was not found: " + arrDivs[i]);
}
}

Categories