JavaScript infinite loop upon clicking "Next" button - javascript

Been a while since I last did JavaScript, but school forced us into a JavaScript project. So here I am, making a simple quiz game. Coming along quite nicely, yet I'm experiencing issues with probably something terribly simple.
var useranswers = new Array();
var imgArray = new Array();
var answered = 0;
var currentQuestion = 0;
function renderQuizViaArray()
{
document.writeln('<h1>' + questions[currentQuestion] + '</h1>');
for(i=0; i < choices[currentQuestion].length; i++)
{
document.writeln('<input type="radio" name="answer_' + currentQuestion + '" value="1" id="answer_' + currentQuestion + '_' + i + '" class="question_' + currentQuestion + '" onclick="submitAnswer(' + currentQuestion + ', this, \'question_' + currentQuestion + '\', \'label_' + currentQuestion + '_' + i + '\')" /><label id="label_' + currentQuestion + '_' + i + '" for="answer_' + currentQuestion + '_' + i + '"> ' + choices[currentQuestion][i] + '</label><br />');
}
document.write('<input type="submit" value="NEXT" onclick="nextQuestion()" />');
}
function nextQuestion()
{
currentQuestion++;
renderQuizViaArray();
}
Whenever I click the "NEXT" button, it loads the second question (Element[1]) from an Array as well as the answers of another Array onto the screen. But the page remains in an infinite loading state and Firebug gives the message: "Reload to activate window console"
Anyone?

I have probably found the issue, but no idea how to fix it.
As soon as I click the "NEXT" button, it executes the function renderQuizViaArray();. That's where it's completely messing up.. am I missing something?
What I basically want is, that the current displayed text gets updated with data of the next question including the answers.
These are the files it contains:
quiz.html: http://rapidimg.org/server/files/50ab9c326115cKAUf6S.png ........ quiz_questions.js: http://rapidimg.org/server/files/50ab9c536ed44UWhV54.png ......... quiz_functions.js: Shown in main post

don't use
for(i=0; i < choices[currentQuestion].length; i++)
use
for(i=0, j=choices[currentQuestion].length; i < j; i++)

Related

call javascript function through dropdown list

How can I go about calling this function through a dropdown menu and the for loop catching all data and not just the last? I've tried some things and all I would get is the last bit of information. Thank you in advance.
<script>
function hey(){
for (i = 1; i < radio.length; i++){
document.write('<div class="dell"><img class="dell3" align="left" src=images/' + radio[i].image + '> <div class="space"> <font size="4">' + i + '. ' + radio[i].name + '</font></br><font color="silver">' + radio[i].category + '</br>' + radio[i].address + '</br>' + radio[i].citystate + '</font></div> </div>');
}
}
</script>
Add class to every item of <select>(<option>).
Get nodelist of option-elements:
const optionList = document.querySelectorAll('.class');
And for each element add event listener with desired function:
optionList.forEach(item => item.addEventListener('event', fucntion(){}));
Edit your code a bit because it's confusing to scroll.

Remove Radio Buttons from a Quiz

We are trying to get a Quiz written in Javascript running on our site. We need to remove Radio buttons because currently, they are not linking through to the next question.
Here is the page in question:
http://stephanieshipper.com/test/
And below is the piece of code from the .js file that contains the Radio buttons. How would I remove these without breaking the rest of the functionality? So far, when I have taken out the Radio buttons, the text links also break.
function updates(questions) {
for (i = 0; i < 20; i++) {
$("body").append("<article><p>" + questions[i] + "</p><input id='question-" + (i*10) + "-1' type='radio' order='1' name='question-" + i + "-0'><label for='question-" + (i*10) + "-1'>exactly like me</label><br><input id='question-" + (i*100) + "-2' type='radio' order='2' name='question-" + i + "-0'><label for='question-" + (i*100) + "-2'>sort of like me</label><br><input id='question-" + (i*1000) + "-3' type='radio' order='3' name='question-" + i + "-0'><label for='question-" + (i*1000) + "-3'>not really like me</label><br><input id='question-" + (i*10000) + "-4' type='radio' order='4' name='question-" + i + "-0'><label for='question-" + (i*1000) + "-4'>not at all like me</label><br></article>");
}
motions();
}
function motions() {
var step = 1;
results = [];
var order;
$("body > article > label").on("click", function() {
$(this).parent().hide(250);
if (step < 20) {
$(this).parent().next().show(250);
order = parseInt($(this).prev().attr("order"));
results[step-1] = order;
step++;
} else {

How to replace current page content on user input?

I am creating a search engine of sorts, using the Wikipedia API to query content. As it currently stands, the user can make a search input and the page returns the top 10 results with links and snippets. I run into difficulty when the user makes another search, in which case the page simply appends the original search results again. I have tried using replaceWith() and html(), but they either prevent the search results from coming through at all (if I put them within the event handler), or they don't get triggered (if they are outside the event handler). I am hoping to achieve a result where the user can make another input and the page will replace the current content with the new search results.
Here is what I have currently:
JS:
var results = [];
$("#search").on("keydown", "#searchinput", function(event) {
if (event.key === "Enter") {
var searchParameter = encodeURIComponent(this.value);
var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";
$.getJSON(link, function(data) {
for (var key in data) {
results.push(data[key]);
}
for (var i = 0; i < 10; i++) {
$("#results").append("<div class=\"resultContent\">" + "<h2>" + "" + results[1][i] + "" + "</h2>" + "<p>" + results[2][i] + "<br/>" + "</p>")
}
})
}
})
HTML:
Feeling Bold? Click Here for a Random Article
<div id="search">
<span>Search:</span>
<input type="text" id="searchinput" autocomplete="off"></input>
</div>
<div id="results"></div>
Thanks for the help!
You can remove the current results just before your loop:
$("#results").empty();
for (var i = 0; i < 10; i++) {
$("#results").append("<div class=\"resultContent\">" + "<h2>" + "" + results[1][i] + "" + "</h2>" + "<p>" + results[2][i] + "<br/>" + "</p>")
}

How to insert a string into an array of text inputs?

Basically, I have a large string that i am splitting, then splitting again.
I then need to use the smallest split array to place its elements into text inputs on my page.
This is my Javascript
var splitquestions = vals[2].split('\n');
//Loop to go through all current questions
for (var i = 0; i < splitquestions.length - 1; i++)
{
//trigger a question add where a single question data can be added into
$( "#add" ).trigger('click');
//split current question into separate items
var s = splitquestions[i].split(',');
//Loop to go over all sections in a question
var count = 0;
for(var j = 0; j < s.length; j++)
{
count = count + 1;
var qs = document.getElementById('questions[' + j +'][' + count + ']').value;
qs = s[j];
}
}
There will be many questions on the page, depending how many the user will like to add. Each new question block will consist of a question, 3 wrong answers, and 1 correct answer.
The part that is going wrong is within the last loop. This is where I need to grab each individual element within the 's' array, and place it within each text input.
This is how the raw data is displayed before it is split by the 'splitquestions' variable:
question1,incorrect-answer1,incorrect-answer2,incorrect-answer3,correct-answer
question2,incorrect-answer1,incorrect-answer2,incorrect-answer3,correct-answer
question3,incorrect-answer1,incorrect-answer2,incorrect-answer3,correct-answer
As you can see from above, each question is separated by a line-break, being \n, then each individual part is comma separated.
Each question input has a multidimensional variable assigned to its ID. For example, using the data above, the first line of data, along with the very first element (being question1) would be question[1][1]. Another example would be 'incorrect-answer1' on the third line of data, which would be question[3][2]. The first number is the question number, and the second number is the element number.
I hope that I've explained this well enough, since I am a little confused on how to explain it myself since I am new to multidimensional arrays and loops inside loops. So please, if you need any additional information, just post a comment and I'll do my best.
If needed, this is the function that creates the question elements dynamically:
function dynamicForm () {
//set a counter
var i = $('.dynamic-input#form-step2').length + 1;
//alert(i);
//add input
$('a#add').click(function () {
$('<table><tr><td><p><span class="left"><input type="text" class="dynamic-input" name="questions[' +i +'][1]" id="' + i + '" placeholder="Question" /></span>' + '<span class="right"><input type="text" class="dynamic-input" name="questions[' +i +'][2]" id="' + i + '" placeholder="Distraction 1" /><br /><input type="text" class="dynamic-input" name="questions[' +i +'][3]" id="' + i + '" placeholder="Distraction 2" /><br /><input type="text" class="dynamic-input" name="questions[' +i +'][4]" id="' + i + '" placeholder="Distraction 3" /><br /><input type="text" class="dynamic-input" name="questions[' +i +'][5]" id="' + i + '" placeholder="Correct Answer" /><br />Remove</span></p></td></tr></table>').fadeIn("slow").appendTo('#extender');
i++;
$("a:contains('Remove')").click(function () {
$(this).parent().parent().remove();
});
return false;
});
//fadeout selected item and remove
$("#form-step2.dynamic-input").on('click', 'a', function () {
$(this).parent().fadeOut(300, function () {
$(this).empty();
return false;
});
});
}
After further discussions with the OP, we fixed the code ended up being what's below. Basically, his input numbers are starting at index 1 instead of 0, so that was one of the issues. He was also trying to select by id while the inputs in question only had a name attribute.
//Loop to go over all sections in a question
for (var j = 1, len = s.length; j <= len; j++) {
$('input[name="questions[' + (i + 1) + '][' + j + ']"]').val(s[j - 1]);
}

jquery append() works in chrome debugger and on IE, but not in Chrome

I have a strange situation where my code works in the debugger (Chrome), and also work on IE 9, but doesn't work in chrome, and in Firefox. All I'm trying to do is to append a bunch of list elements to a list.
HTML:
<div id="FriendSelector">
<ul></ul>
</div>
JS:
var friends = []; //this gets loaded with about 600 friend objects (name, icon, id) earlier
function openFriendSelector() {
var $friendSelector = $('#FriendSelector');
$friendSelector.show();
bindFriends();
}
function bindFriends() {
var $list = $('#FriendSelector ul');
for (i = 0; i < friends.length; i++) {
var friend = '<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
$list.append(friend);
}
}
When I click the button that opens the FriendSelector DIV (initially hidden), I see a blank DIV, however, if I close the popup and re-open it, the friends are there...
Any help is appreciated.
Found the issue. The array was taking a few seconds to get loaded (via ajax). So, after the page loads, if I wait a couple seconds and then open the div, it works. Which explains why it worked in the debugger.
Try to avoid so many .append() calls at once, so replace your following code:
for (i = 0; i < friends.length; i++) {
var friend = '<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
$list.append(friend);
}
for this one:
for (i = 0, friend=''; i < friends.length; i++) {
friend +='<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
}
$list.append(friend);
UPDATE:
Try to load friends prior to showing the div, like this:
function openFriendSelector() {
bindFriends();
}
function bindFriends() {
var $list = $('#FriendSelector ul');
for (i = 0, friend = ''; i < friends.length; i++) {
friend = '<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
}
$list.append(friend);
$list.parent().show();
}

Categories