JavaScript - Quiz Debugging
In short, what's wrong with this? I'm sure you'll test it, but it just posts the JS inside the Bold tag instead of the grade. This includes the innerHTML script.
Code: <html> <head> <script type="text/javascript"> function grade() { var tot = 1; var g = 0; var qId0 = document.getElementById('0').value; if (qId0 == "t") { g = g + 1; } g = g / tot; g = g * 100; document.getElementById("grade").innerHTML = grade; } </script> </head> <body> <b id="grade">Your Grade Here</b> <ol> <li><select id="0"> <option value="d">Test Question</option> <option value="f">false</option> <option value="t">true</option> <option value="f">false</option> </select> <button onclick="grade()">Submit</button> </body> </html> When I hit "submit" with the right answer, I get: function grade() { var tot = 1; var g = 0; var qId0 = document.getElementById('0').value; if (qId0 == "t") { g = g + 1; } g = g / tot; g = g * 100; document.getElementById("grade").innerHTML = grade; } When I hit "submit" with the wrong answer, I get the same. Can someone explain this to me and tell me how to fix it? (Also, I would appreciate it if you could point out any unrelated bugs you come across ) Similar TutorialsI've been working on that for days, and can't find the problem. Could one of you help? I wrote a low-level digit-shift cipher, but the script doesn't work. Code: <head> <script type="text/javascript"> function ciphertext() { var t = document.getElementById.('t') t = t.toUpperCase() var n = 0 var o = "" if(n=0) { o=o+t n=n+1 } if(n=1) { if(t=="A") o=o+"B" if(t=="B") o=o+"C" if(t=="C") o=o+"D" if(t=="D") o=o+"E" if(t=="F") o=o+"G" if(t=="G") o=o+"H" if(t=="H") o=o+"I" if(t=="I") o=o+"J" if(t=="J") o=o+"K" if(t=="K") o=o+"L" if(t=="L") o=o+"M" if(t=="M") o=o+"N" if(t=="N") o=o+"O" if(t=="O") o=o+"P" if(t=="P") o=o+"Q" if(t=="Q") o=o+"R" if(t=="R") o=o+"S" if(t=="S") o=o+"T" if(t=="T") o=o+"U" if(t=="U") o=o+"V" if(t=="V") o=o+"W" if(t=="W") o=o+"X" if(t=="X") o=o+"Y" if(t=="Y") o=o+"Z" if(t=="Z") o=o+"A" else o=o+t n=n-1 } document.getElementById('op').innerHTML = o.value } </script> </head> <body> <b id="op">This is your result</b> <input type="text" id='t' /> <button onclick="ciphertext()">Submit</button> </body> I've been working on that for days, and can't find the problem. Could one of you help? (Pardon me if I am being blunt, but why doesn't this work?) I've been messing with this for hours and I can't seem to find where I've gone wrong with it, I think I need a fresh pair of eyes to give it a look over. Anyways here's my entire piece of code. I know it's a lot to look at but if anyone can help me get this working that would be great, it's starting to give me a headache just to look at it. Anyways from what I can tell the problem is somewhere in the wDesQuote() function but I can't seem to pin it down. Code: //Start Ajax Code var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID){ if(XMLHttpRequestObject){ var obj = document.getElementById(divID); XMLHttpRequestObject.open("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function(){ if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){ obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send(null); } } //End Ajax Code //Start Div Updater function textUpdate(text, divID){ if(XMLHttpRequestObject){ var obj = document.getElementById(divID); obj.innerHTML = text; XMLHttpRequestObject.send(null); } } //End Div Updater //Money Formater function roundNumber(num, dec) { var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); return result; } //End Money Formater function wDesQuote() { var eBizCard = document.getElementById('eBizCard').checked; var basic = document.getElementById('basic').checked; var mobile = document.getElementById('mobile').checked; var pages = document.getElementById('pages').value * 20; var host = document.getElementById('hostY').checked; var cTemp = document.getElementById('cTemp').checked; var anime = document.getElementById('anime').checked; var addMobile = document.getElementById('addMobile').checked; var eComP = document.getElementById('eComP').checked; var eComI = document.getElementById('eComI').value; var eComQ = 0; var forum = document.getElementById('forum').checked; var blog = document.getElementById('blog').checked; var wUpd = document.getElementById('wUpd').checked; var bUpd = document.getElementById('bUpd').checked; var mUpd = document.getElementById('mUpd').checked; var nUpd = document.getElementById('nUpd').checked; var logo = document.getElementById('logo').checked; var bCard = document.getElementById('bCard').checked; var pCard = document.getElementById('pCard').checked; var brochure = document.getElementById('brochure').checked; var mTotal = 0; var uTotal = 0; if(eBizCard == true && host == true){ uTotal = 149.95; mTotal = 9.95; }else if(eBizCard == true && host == false){ uTotal = 149.95; mTotal = 0; }else if(mobile == true && host == true){ uTotal = 299.95; mTotal = 9.95; }else if(mobile == true && host == false){ uTotal = 299.95; mTotal = 0; }else{ eBizCard = 0; mobile = 0; basic = 499.95; if(host == true){ host = 9.95; } else{ host = 0; } if(cTemp == true){ cTemp = 100; }else{ cTemp = 0; } if(anime == true){ anime = 150; }else{ anime = 0; } if(addMobile == true){ addMobile = 275; }else{ addMobile = 0; } if(eComP == true){ eComP = 200; eComQ = roundNumber(eComI * 0.59,2).toFixed(2); if(eComQ == "NaN"){ alert("Please enter numbers only into the item quantity box"); break; } }else{ eComP = 0; eComI = 0; } if(forum == true){ forum = 50; }else{ forum = 0; } if(blog == true){ blog = 50; }else{ blog = 0; } if(wUpd == true){ wUpd = 175; }else{ wUpd = 0; } if(bUpd == true){ bUpd = 100; }else{ bUpd = 0; } if(mUpd == true){ mUpd = 60; }else{ mUpd = 0; } if(nUpd == true){ nUpd = 0; }else{ nUpd = 0; } if(logo == true){ logo = 75; }else{ logo = 0; } if(bCard == true){ bCard = 90; }else{ bCard = 0; } if(pCard == true){ pCard = 140; }else{ pCard = 0; } if(brochure == true){ brochure = 280; }else{ brochure = 0; } } var uTotal = pages + cTemp + anime + addMobile + eComP + eCompQ + forum + blog + wUpd + bUpd + mUpd + nUpd + logo + bCard + pCard + brochure; var mTotal = host + mUpd + bUpd + wUpd + nUpd; if(mTotal == 0){ document.getElementById('totalDisplay').innerHTML = "Your total is $" + uTotal; }else{ document.getElementById('totalDisplay').innerHTML = "Your total is $" + uTotal + " a monthly fee of $" + mTotal; } } I'm used to PHP, where I can use var_dump to find out about a variable wherever I call it. Or, having the script crash entirely and give me an idea of what mistake I made, when I made a mistake. With JS, neither of those appear to be true. I was told I can use console.log or console.dir to get something similar to var_dump, but as you can see: it's giving me no output. I need a way to help me find the mistakes I make. How can I get console.dir to work? See the image below: Large image: http://i.imgur.com/4cw89OO.png what is wrong with this Code: function addfavorites(classid,userid) { // alert("here"); var urltoajax = "addfavorites.php?j=1&classid="+ classid + "&userid="+ userid; urltoajax = urltoajax + '&rnd=' + Math.round(Math.random() * 10000) alert(urltoajax); $.ajax({ url: urltoajax, cache: false, success: function(html) { $("#message").html(html); } }); //alert('here 2'); } i get an error Object doesn't support this property or method This question hovers between PHP and JavaScript, but I think it fits here a little better. I've got a web app that does a lot of asynchronous calls to various PHP pages. I'm familiar with using an iFrame or div to hold a controller, then making forms post to that controller so you can see the output. However, I'm not doing a lot of submitting forms. Typically, I utilize the onclick event of various elements to initiate an XmlHttpRequest that jumps over to a PHP page and back. I'm looking for a way to easily debug my PHP code. Right now I'm using Firebug (on Firefox) to look at the HTTP requests. I can see the post data and response and all that, which is good. However, it requires a good amount of clicking and time to get to that data. Is there an easier way to do this? Ideally I'd love to include some sort of debug window that displays all of the PHP controller errors and things that I echo out. I am trying to debug this with FireBug Code: function chapter12_nodeOne() { //create an element var element = document.createElement('input'); //set some attributes element.setAttribute('type', 'button'); element.setAttribute('value', 'submit'); //appendd the element into a DIV document.getElementById('myDiv').appendChild(element); //uses EventUtil to attach an event listener (1) EventUtil.addHandler(element, 'click', function() { alert('added event handler') }); } var EventUtil = { (2)addHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.addEventListener) { element.addEventListener(type, handler, false); } //if user is browsing with IE else if (element.attachEvent) { element.attachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.removeEventListener) { element.removeEventListener(type, handler, false); } //if user is browsing with IE else if (element.detachEvent) { element.detachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = null; } }, preventDefault: function(event) { if(event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } }; I put a breakpoint on the line marked with (1), I am trying to go to line (2) with all the available options FireBug gives, but unfortunately I get the end of chapter12_nodeOne function. Any ideas why? Hi everybody. I've been trying to figure out how to fix the following error I get in the latest Internet Explorer for marinebio.org: Message: 'this.submenus[...].getElementsByTagName(...).0' is null or not an object Line: 547 Char: 3 Code: 0 URI: http://marinebio.org/_n/s/main.js The code at line 547 in main.js is: Code: this.submenus[i].getElementsByTagName("span")[0].onclick = function() { in the function: Code: SDMenu.prototype.init = function() { var mainInstance = this; for (var i = 0; i < this.submenus.length; i++) this.submenus[i].getElementsByTagName("span")[0].onclick = function() { mainInstance.toggleMenu(this.parentNode); }; if (this.markCurrent) { var links = this.menu.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) if (links[i].href == document.location.href) { links[i].className = "current"; break; } } if (this.remember) { var regex = new RegExp("sdmenu_" + encodeURIComponent(this.menu.id) + "=([01]+)"); var match = regex.exec(document.cookie); if (match) { var states = match[1].split(""); for (var i = 0; i < states.length; i++) this.submenus[i].className = (states[i] == 0 ? "collapsed" : ""); } } }; I've been using the Dynamic Drive's Slashdot sliding menu script for at least a year without any problems. All pages validated before the ads were added. I've pulled nearly all other scripts but it still errors out. Works fine in FF and Chrome. Going to strip the home page to nothing and start building it back but if anyone has any ideas, I'd really appreciate it. Maybe it's time to upgrade the vertical sliding menu script entirely, if anyone can recommend a better one, that would be great too. I know just enough javascript to be dangerous apparently.... first of all, hello all i found this forum while running out of ideas and being extremely desperate to fixing a probably small javascript error in a script. the script is supposed to open a small form window that allows the user to input an email address and update it to proceed. the form item is initially unchecked, but as the user clicks it and enter his email address, it updates the value of the email address and the box becomes "checkable". the problem is that with both IE and firefox, the box doesn't close again, doesn't get checkable and basically doesn't work. in the firefox debugging console, I found the following error: Quote: Error: document.getElementById(input_array[i]) is null Source File: sell_item.php Line: 1106 does anyone have an idea what could be wrong? the part responsible in the javascript for this section is: Code: <script language="javascript"> function pg_popup_open(id) { if (document.getElementById(id).style.display == 'block') { document.getElementById(id).style.display = 'none'; } else { document.getElementById(id).style.display = 'block'; } return false; } function pg_update_settings(id, input_array) { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var url = '' + 'ajax_files/direct_payment_box.php'; var action = url + '?id=' + id + '&user_id=' + 100001; var chk_disabled = false; for ( var i in input_array ) { action += '&' + input_array[i] + '=' + document.getElementById(input_array[i]).value; if (document.getElementById(input_array[i]).value == '') { chk_disabled = true; } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { var response = xmlHttp.responseText; } }; xmlHttp.open("GET", action, true); xmlHttp.send(null); document.getElementById('checkbox_' + id).disabled = chk_disabled; if (chk_disabled == true) { document.getElementById('checkbox_' + id).checked = false; } document.getElementById(id).style.display = 'none'; return false; } </script> and the html code that is supposed to pop up the box is: Code: <input type="checkbox" name="payment_gateway[]" id="checkbox_pg_paypal" value="1" disabled> <span class="contentfont"><a href="javascript:;" onclick="pg_popup_open('pg_paypal');">PayPal</a></span> <script language="javascript"> var array_pg_paypal = new Array(); array_pg_paypal[0] = 'pg_paypal_email';</script> <div class="smallfont"><b>PayPal Email Address</b><br> <input type="text" name="pg_paypal_email" id="pg_paypal_email" value="" /></div> <div align="right"><input type="button" value="Proceed" onclick="pg_update_settings('pg_paypal', array_pg_paypal);" /></div> i understand this is asking a lot, but if someone has a spare second that is a javascript guru, i promise i will name my first born after you!! lol This page should work, but it doesn't. My debugging says that I have a invalid character on line 2 and on line 39 it is "object expected". Here's the page: <HTML> <HEAD> <TITLE>The Golf Page</TITLE> <STYLE> BODY {font-family:Arial, Helvetica, sans-serif; font-size: 18pt; color:blue; background-color:rgb(255,255,128)} </STYLE> <SCRIPT SRC="Ball.gif"> var x = new Array(-395, -389, -383, -377, -371, -365, -359, -353, -346, -340, -334, -328, -322, -316, -310, -304, -297, -291, -285, -279, -273, -267, -261, -255, -248, -242, -236, -230, -224, -218, -212, -206, -199, -193, -187, -181, -175, -169, -163, -157, -150, -144, -138, -132, -126, -120, -114, -108, -101, -95, -93, -91, -88, -86, -83, -81, -78, -76, -73, -71, -69, -66, -64, -61, -59, -56, -54, -51, -49, -47, -44, -42, -39, -37, -34, -32, -29, -27, -24, -22, -20, -17, -15, -12, -10, -7, -5, -2, 0); var y = new Array(-300, -300, -300, -299, -298, -297, -296, -294, -292, -290, -288, -285, -282, -279, -276, -272, -268, -264, -260, -255, -250, -245, -240, -234, -228, -222, -216, -209, -202, -195, -188, -180, -172, -164, -156, -147, -138, -129, -120, -110, -100, -90, -80, -69, -58, -47, -36, -24, -12, 0, -5, -10, -14, -18, -22, -25, -29, -32, -34, -37, -39, -41, -43, -45, -46, -47, -48, -48, -48, -48, -48, -48, -47, -46, -45, -43, -42, -40, -37, -35, -32, -29, -26, -23, -19, -15, -11, -6, 0); index=0 function moveBall() { if(index <=[x.length-1]) { placeIt("Ball", x[index], y[index]); index++; setTimeout("moveBall()", 5); } else { ("showIt()", 5); setTimeout("showIt('Slogan')", 5); setTimeout("showIt('Slogan1')", 10); setTimeout("showIT('Marquee')", 15); } } </SCRIPT> </HEAD> <BODY onLoad="moveBall(Ball);"> <DIV ID="Marquee" visibility:hidden font-family: Time New Roman, Times, serif; font-style:italic> <CENTER> <MARQUEE BGCOLOR="#BBBBBB"> A beautiful day for GOLF...Sunny...No WINDS...TEMP:68-70 </MARQUEE> </CENTER> </DIV> <SCRIPT SRC="Golf.js"></SCRIPT> <DIV ID="Title" STYLE="border-left:1px solid blue; border-right:3px solid blue; border-top:1px solid blue; border-bottom:3px solid blue; padding-left:395;padding-top:260;padding-bottom:0; background-color:rgb(0,255,0)"> THE G<SPAN ID="Ball" position:relative; left:0; top:0><IMG SRC="Ball.gif" BORDER=0 width="17" height="17"></SPAN>LF PAGE </DIV> <DIV ID="Slogan" STYLE="color:black; font-family: Times New Roman, Times, serif; font-style:italic; font-weight:bold; position:absolute; left:120; top:100; z-index:2; visibility:hidden"> Your Online Source of Golf Equipment </DIV> <DIV ID="Slogan2" STYLE="color:white; font-family: Times New Roman, Times, serif; font-style:italic; font-weight:bold; position:absolute; left:121; top:101; z-index:1; visibility:hidden"> Your Online Source of Golf Equipment </DIV> </BODY> </HTML> The function moveBall and its contents should be checked as well, although it should be correct. But the page won't load properly. The marquee is suposed to be hidden until the function executes, and it is displayed. As far as I know the only errors are in the onLoad and function, everything else is right. Any help would be appreciated. Thanks Hello, I'm a student web developer. I'm debugging some JavaScript code I just created that simply extracts a table, reorders it and replaces it when the user clicks on a button ('Order results' - top right of the table). (It's a small script). It's for a PHP based polling application, completely of my own creation, which is under construction (only the JavaScript doesn't work). You can see all the code if you use Firebug. Go to the following link and vote for something; that will take you to a page the JavaScript is located. http://www.samuellockyer-development...s/examples.php (I'm linking because I think the context of the page may help.) (Notice the type error alert.) (Update: Not anymore.) (There are NO syntax errors.) You will find the area of the bug quickly by looking at the comments. (Marked by !!BUG!!) (Update: Not anymore, look at the posts below to find them now.) I am very new to JavaScript, but I wrote all the code, so I will be able to answer questions easily. This is a last resort by the way, I need this to work within about two days and I would be SO grateful for any help!! You can vote as many times as you like - I can just zero everything before I demo the app. I've been playing around with a madlibs exercise while trying to learn simple javascript. I have three input boxes and a button display an alert containing the input from the boxes. Am I right to be assigning variable names to the values from the text boxes and then referencing those variables in my alert? I'm sorry if this is a dumb question but I've been working on it for hours and can't get past this point. Inset a name: <input type="text" id="textbox1" size="10"/> </br> Insert a verb : <input type="text" id="textbox2" size="10"/> </br> Insert a place: <input type="text id="textbox3" size="10"/> <input type="button" value="CLICK WHEN FINISHED" onClick="name = document.getElementById('textbox1').value; verb = document.getElementById('textbox2').value; place = document.getElementById('textbox3').value; alert('Mad Lib :' + name + " " + verb + " " + place);" /> Hello, Could someone please help me modify this code. How can I have more then one answer correct in the fill in the blank question? For example: Green/Red is my favorite color. Thank you Code: <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM INCOMPATIBLE BROWSERS // STOP HIDING FROM INCOMPATIBLE BROWSERS --> </SCRIPT> <HTML> <HEAD> <TITLE>Short Quiz</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM INCOMPATIBLE BROWSERS number_questions = 2; answer_list = new Array(number_questions); answer_list[0] = "Red"; answer_list[1] = "New York Jets"; response = new Array(number_questions); function setAnswer(question, answer) { response[question] = answer; } function CheckAnswers() { var correct = 0; for (var i = 0; i < number_questions; i++) { if (response[i] == answer_list[i]) { correct++; } } alert("You got " + correct + " of " + number_questions + " questions correct!"); } // STOP HIDING FROM INCOMPATIBLE BROWSERS --> </SCRIPT> </HEAD> <BODY BGCOLOR = #EEFFE8> <FONT FACE="Arial" SIZE=6>Short Quiz</FONT><BR> <HR SIZE=5 WIDTH=100%> <FONT FACE="Arial" SIZE=3> <FORM> <B>1. <INPUT TYPE=text NAME=question0 size=30 onChange="setAnswer(0, this.value)"> is my favorite color</B><P> <BR><P> <B>2. For what NFL team did Joe Namath play?</B><P> <INPUT TYPE=radio NAME=question1 VALUE="New York Giants" onClick="setAnswer(1,this.value)">New York Giants<BR> <INPUT TYPE=radio NAME=question1 VALUE="New England Patriots" onClick="setAnswer(1,this.value)">New England Patriots<BR> <INPUT TYPE=radio NAME=question1 VALUE="New York Jets" onClick="setAnswer(1,this.value)">New York Jets<BR> <INPUT TYPE=radio NAME=question1 VALUE="Buffalo Bills" onClick="setAnswer(1,this.value)">Buffalo Bills<BR><P> </FORM> <FORM> <INPUT TYPE="button" NAME="check" VALUE="Check Answers" onClick=CheckAnswers()> </FORM> </FONT> </BODY> </HTML> first of all, heres my body code (dont mind the questions, theyre in greek): Code: <form name="htmltest" onSubmit="return check1() && check2() && check3() && check4() && check5() && check6() && results()"> <b>1) Τι σημαίνει HTML?</b><br> <input type="radio" name="q1" value="a" onclick="score[1]=0">a) Home Tool Markup Language<br> <input type="radio" name="q1" value="b" onclick="score[1]=0">b) Hyperlinks and Text Markup Language<br> <input type="radio" name="q1" value="c" onclick="score[1]=1">c) Hyper Text Markup Language<br> <b>2) Διάλεξε το σωστό HTML tag για την μεγαλύτερη επικεφαλίδα:</b><br> <input type="radio" name="q2" value="a" onclick="score[2]=0">a) < h6 ><br> <input type="radio" name="q2" value="b" onclick="score[2]=0">b) < head ><br> <input type="radio" name="q2" value="c" onclick="score[2]=1">c) < h1 ><br> <b>3) Ποιο είναι το σωστό HTML tag για line break?</b><br> <input type="radio" name="q3" value="a" onclick="score[3]=0">a) < break ><br> <input type="radio" name="q3" value="b" onclick="score[3]=0">b) < lb ><br> <input type="radio" name="q3" value="c" onclick="score[3]=1">c) < br ><br> <b>4) Διάλεξε το σωστό HTML tag για να κάνεις bold κάποια γράμματα:</b><br> <input type="radio" name="q4" value="a" onclick="score[4]=0">a) < bold ><br> <input type="radio" name="q4" value="b" onclick="score[4]=1">b) < b ><br> <input type="radio" name="q4" value="c" onclick="score[4]=0">c) < text.bold ><br> <b>5) Ποιος είναι ο σωστός τρόπος για να δημιουργήσετε έναν υπερσύνδεσμο;</b><br> <input type="radio" name="q5" value="a" onclick="score[5]=0">a) < a url="http://www.unipi.gr">Unipi.gr < / a><br> <input type="radio" name="q5" value="b" onclick="score[5]=1">b) < a href="http://www.unipi.gr">Unipi.gr< / a><br> <input type="radio" name="q5" value="c" onclick="score[5]=0">c) < a >http://www.unipi.gr"< / a><br> <b>6) Ποια απο τα παρακάτω HTML tag απευθύνονται όλα σε πίνακα?</b><br> <input type="radio" name="q6" value="a" onclick="score[6]=0">a) < table >, < head >, < tfoot ><br> <input type="radio" name="q6" value="b" onclick="score[6]=0">b) < table >, < tr >, < tt ><br> <input type="radio" name="q6" value="c" onclick="score[6]=1">c) < table >, < tr> , < td ><br> <input type="submit" value="Αξιολόγηση"> <input type="reset" value="Reset"><br><br> </form> and here's my javascript code Code: function check1() { var radio_choice=false; for (counter=0; counter < htmltest.q1.length; counter++) { if (htmltest.q1[counter].checked ) radio_choice=true; } if (!radio_choice) { alert("Παρακαλώ απαντήστε σε όλες τις ερωτήσεις") return (false); } return(true); } function check2() { var radio_choice=false; for (counter=0; counter < htmltest.q2.length; counter++) { if (htmltest.q2[counter].checked ) radio_choice=true; } if (!radio_choice) { alert("Παρακαλώ απαντήστε σε όλες τις ερωτήσεις") return (false); } return(true); } function check3() { var radio_choice=false; for (counter=0; counter < htmltest.q3.length; counter++) { if (htmltest.q3[counter].checked ) radio_choice=true; } if (!radio_choice) { alert("Παρακαλώ απαντήστε σε όλες τις ερωτήσεις") return (false); } return(true); } function check4() { var radio_choice=false; for (counter=0; counter < htmltest.q4.length; counter++) { if (htmltest.q4[counter].checked ) radio_choice=true; } if (!radio_choice) { alert("Παρακαλώ απαντήστε σε όλες τις ερωτήσεις") return (false); } return(true); } function check5() { var radio_choice=false; for (counter=0; counter < htmltest.q5.length; counter++) { if (htmltest.q5[counter].checked ) radio_choice=true; } if (!radio_choice) { alert("Παρακαλώ απαντήστε σε όλες τις ερωτήσεις") return (false); } return(true); } function check6() { var radio_choice=false; for (counter=0; counter < htmltest.q6.length; counter++) { if (htmltest.q6[counter].checked ) radio_choice=true; } if (!radio_choice) { alert("Παρακαλώ απαντήστε σε όλες τις ερωτήσεις") return (false); } return(true); } var score = new Array; function results() { var i, total; total = 0; for(i=1;i<=6;i++) { total += score[i]; } window=window.open("resultshtml.html","answers","width=400px,height=700px"); document.write(total); } what i want is, first of all an easier way to get an alert if not all questions are answered because mine (6 different functions) is a bit long. Also, when you press submit, a new window must pop up (not an alert box) with your score and the correct answers. I managed to get the window to pop up but i cant make it show the variable "total" value which contains the score (from the function "results"). Any ideas? hi, I'm a new guy to computer science and info system and I am taking an intro class to it right now. I was asked to make a simple "enter the word in the box" quiz and I can't get the output! it's driving me crazy and I get "ur score is [object HTMLInputElement]out of 3" at the bottom when I had it say, "Your score is:".. here is my html coding and no, I'm not asking for anyone to do my homework. I just want to make this work! be easy. NOTE: I'm using Apple over again because I want to get the coding down and then I will change up the quiz and the answers Code: <html> <head> <title> COMSC 100 Assignment 9 by Me </title> <script> function getInputAsText(_id){return document.getElementById(_id).value} function getInputAsNumber(_id){return parseFloat(document.getElementById(_id).value)} function setOutput(_id, _value){document.getElementById(_id).value = _value} function calculate() { // declare all variables var myResult1 var myResult2 var myResult3 var resultAsText // get variable's value myAnswer1= getInputAsText("myResult1") myAnswer2= getInputAsText("myResult2") myAnswer3= getInputAsText("myResult3") // perform concatenation if (myAnswer1.toLowerCase() == " Apple" .toLowerCase()) { score= score + 1 // got this one right myResult1= "correct" } else { myResult1 = "Wrong! It's Apple" } if (myAnswer2.toLowerCase() == "Apple".toLowerCase()) { score= score + 1 // got this one right myResult2 = "correct" } else { myResult2 = "Wrong! it's Apple" } if (myAnswer3.toLowerCase () == "Apple".toLowerCase()) { score = score + 1 //got this one right myResult3 = "correct" } else { myResult3 = "Wrong! It's Apple" } // write output value setOutput("score", "Your score is " + score + "out of 3") setOutput ("myResult1",myResult1) setOutput ("myResult2",myResult2) setOutput ("myResult3",myResult3) } </script> </head> <body> Directions:<br> Answer the three questions and press go <br> Your score will appear<br> Input values:<br> 1. A byte is how many bits?<input id="myResult1"><br> 2.Steve Jobs heads what company?<input id="myResult2"><br> 3.Bill Gates heads what company? <input id="myResult3"><br> <input type="submit" value="go" onclick="calculate()"><br> Output<br> Result #1:<input id= "myResult1" size="25"><br> Result #2:<input id= "myResult2" size="25"><br> Result #3:<input id= "myResult3" size="25"><br> Your sco <input id= "score" size="25"> </body> </html> Hi, I am looking for a javascript quiz script that will allow me to grade individual sections of a quiz rather than grading the quiz as a whole. I am looking to setup an online test consisting of a number of sections but the output must grade each section individually. Any help apprecaited! sorry this post is duplicated, the original post:http://www.codingforums.com/showthread.php?t=261488
Hello all, * I'm very new to javascript and working on a quiz game. Theres a set of code im working on but i need help, and greatly appreciate any help. * After every questions, there is a tick or wrong animation/image that should pop over the answer card. I created the gif file one for a tick and one for a wrong: http://www.freeimagehosting.net/cqn91 http://www.freeimagehosting.net/v74v6 *By right the user should not be able to click on the answer cards anymore after finishing the quiz. For now the score keeps going up although the quiz is done. And after the quiz is done, a button should direct the user to the DetailedResult page, instead of the popup. *How to change the popup into a Html(DetailedResult) page, and instead of a text eg.(resent.jpg), how can I make the real image show, and if the qn is correct, how can I place a tick and if the qn is wrong how can I place a wrong image. Ive created both images. tick image==>http://i1069.photobucket.com/albums/...ttica/tick.jpg wrong image==>http://i1069.photobucket.com/albums/...ca/wrong-1.jpg *Suppose at the bottom of the html page, should have a button for the user to retry only wrong answers. *And how do i keep updating the user score for each attempt he tries on the table. Below are a set of code i'm working on, and another set of Html layout(DetailedResult) which i intend to achieve. Code: <!DOCTYPE HTML> <html> <head> <title> Card Test </title> <style> img { margin:7px; } #Question { text-align:left; font-family:"Vladimir Script"; font-size:40px; } </style> <script type="text/javascript"> // For: http://www.codingforums.com/private....pm&pmid=124136 var baseURL = 'http://s1069.photobucket.com/albums/u475/felettica/'; var questions = [ // format [pic,[image1,imag2,image3]], ['happy.jpg', ['*|delight.jpg','|sad.jpg','|confuse.jpg']], // 0 ['angry.jpg', ['|sad.jpg','*|resent.jpg','|joyful.jpg']], // 1 ['father.jpg',['|sister.jpg','|mum.jpg','*|dad.jpg']], // 2 ['sports.jpg',['|crying.jpg','*|soccer.jpg','|sleep.jpg']], // 1 ['fruit.jpg', ['*|apple.jpg','|meat.jpg','|bacon.jpg']], // 0 ]; var qNo = 0; var correct = []; function $_(IDS) { return document.getElementById(IDS); } function NextQuestion(IDS) { var response; switch (IDS) { case 'image1' : response = 0; break; case 'image2' : response = 1; break; case 'image3' : response = 2; break; } if (response == currentQuestion[4]) { correct[0]++; alert('Well Done'); } else { alert('Wrong Answer'); } correct.push(currentQuestion.join('|')+'|'+response); // alert(correct.join('\n')); qNo++; if (qNo < questions.length) { $_('score').innerHTML = 'Sco '+correct[0]; showImages(qNo); $_('Question').innerHTML = 'Question: '+(qNo+1); } else { $_('score').innerHTML = 'You had '+correct[0]+' correct answers for '+questions.length+' questions'; DisplayQuizResults(); // alert('End of quizi\n\n'+correct.join('\n')); return; } // I created a two .gif animation of a tick and a wrong // but unsure how to place it so that it appears on the // correct answer image instead of the alertbox. // Tick animation Url==> http://www.freeimagehosting.net/cqn91 // Wrong animation Url==>http://www.freeimagehosting.net/v74v6 // I tried to add a button to direct to the DetailedResult page // which shows the correct and wrong questions but it didnt appear. // It should appear after the alert('End of quiz'); pops up. } var currentQuestion = []; function showImages(ptr) { var tarr = []; var tmp = ''; currentQuestion = []; currentQuestion.push(questions[ptr][0]); // 0 temp_questions = questions[ptr][1].slice(); temp_questions.sort(randOrd); for (var i=0; i<3; i++) { tarr = temp_questions[i].split('|') if (tarr[0] != '') { tmp = i; } // save correct answer currentQuestion.push(tarr[1]); // 1,2,3 // save response order } currentQuestion.push(tmp); // 4 $_("Pic").src=baseURL+currentQuestion[0]; $_("image1").src=baseURL+currentQuestion[1]; $_("image2").src=baseURL+currentQuestion[2]; $_("image3").src=baseURL+currentQuestion[3]; } function randOrd() { return (Math.round(Math.random())-0.5); } window.onload = function() { correct = []; correct.push(0); questions = questions.sort(randOrd); showImages(0); } // Following from: http://www.yourhtmlsource.com/javascript/popupwindows.html function DisplayQuizResults() { var generator=window.open('','name','height=400,width=500'); generator.document.write('<html><head><title>Popup</title>'); generator.document.write('<link rel="stylesheet" href="style.css">'); generator.document.write('</head><body>'); var str = ''; var tarr = []; // correct array format: item +|+ question +|+ answer +|+ response var str = '<h1> Your Results</h1>'; for (var i=1; i<correct.length; i++) { tarr = correct[i].split('|'); // item|img1|img2|img3|ans|resp str += 'Question #'+i; str += ' was: '+tarr[0]; str += '<br>Correct answer was: '+tarr[4] +'('+tarr[tarr[4]*1+1]+')'; if (tarr[4] != tarr[5]) { str += ' but your answer was: '+tarr[5] +'('+tarr[tarr[5]*1+1]+')'; } str += '<p>'; } generator.document.write('<p>'+str+'<p>'); generator.document.write('<p><a href="java_script:self.close()">Close</a> the popup.</p>'); generator.document.write('</body></html>'); generator.document.close(); } </script> </head> <body> <div id="Question">Question: 1</div> <div align="center"> <img id="Pic" src="" height="220" width="321"> <p> <img id="image1" src="" width="269" height="171" onclick="NextQuestion(this.id)"> <img id="image2" src="" width="269" height="171" onclick="NextQuestion(this.id)"> <img id="image3" src="" width="269" height="171" onclick="NextQuestion(this.id)"> <p> <span id="score">Sco </span> <p></div> </body> </html> ================================================ Instead of the popup, instead i thought having it on a Html page (DetailedResult), the layout below ================================================ Code: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style type="text/css"> Table{ position:absolute; left:632px; top:97px; width: 408px; border:1px solid black; } table, td, th { border:1px solid green; } th { background-color:green; color:white; } </style> </head> <body> <table width="472" border="0" cellspacing="0" cellpadding="0"> <!--In the table,the scores of the user should appear for the the current attempt and previous attempts so that the user can track his scores--> <tr> <th width="227" scope="row"><strong>My Attempts</strong></th> <td width="181"> <div align="center">My sco </div></td> </tr> <tr> <th height="19" scope="row">1st Attempt</th> <td><div align="center">4/5</div></td> </tr> <tr> <th scope="row">2nd Attempt</th> <td> </td> </tr> <tr> <th scope="row">3rd Attempt</th> <td> </td> </tr> </table> <h1> My Current Attempt </h1> <p> </p> <p>Question 1: "code to get Qn 1 image" "either tick image or wrong image" </p> <!-- For each qn, its picture will appear and either a tick or wrong image next to it. If the user answer it correctly, then a tick will appear or other wise. The image of the question would be smaller. --> <p>Question 2: "code to get Qn 1 image" "either tick image or wrong image"</p> <p>Question 3: "code to get Qn 1 image" "either tick image or wrong image"</p> <p>Question 4: "code to get Qn 1 image" "either tick image or wrong image"</p> <p>Question 5: "code to get Qn 1 image" "either tick image or wrong image"</p> <p><button type="button">Retry Wrong Question</button><p> <!-- direct page to retry wrong qns once more --> <!-- tick image URL:http://i1069.photobucket.com/albums/...ttica/tick.jpg wrong image URL http://i1069.photobucket.com/albums/...ca/wrong-1.jpg baseURL:http://s1069.photobucket.com/albums/u475/felettica/ --> </body> </html> hi guys, am trying to create online quiz with javascript,but am having problems,the code compiles but when i run nothing appears.i need help pliz. below is my code.please show where edited. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Driving Theory Test</title> <script language="javaScript" type="text/javascript"> //Questions and answers var questions = new Array(); var answers = new Array(); var questionsAsked; var numberOfQuestionsAsked = 0; var numberofQuestionCorrect = 0; var currentQNumber = -1; //define question 1 questions[0] = new Array(); questions[0][0] = "For which purpose is a horn allowed to be used outside built up areas"; questions[0][1] = "As a warning signal"; questions[0][2] = "As an overtaking signal"; // give correct answer Answers[0] = "A"; //define question 2 questions[1] = new Array(); questions[0][0] = "What can be the effects of even small quantities of alcohol"; questions[0][1] = "Delayed reactions"; questions[0][2] = "Reckless driving"; questions[0][3] = "Impairment of hearing and vision"; // give correct answer Answers[1] = "A"; //define question 3 questions[2] = new Array(); questions[0][0] = "What can cause a dangerous situation"; questions[0][1] = "Cutting corners"; questions[0][2] = "Dipping your headlihgts too late"; // give correct answer Answers[2] = "B"; fuction reset quiz() { var indexCounter; currentQNumber = -1; questionsAsked = New Array(); for (indexCounter = 0; indexCounter < questions.length;indexCounter++) { questionsAsked[indexCounter] = false; } numberOfQuestionsAsked = 0; numberOfQuestionsCorrect = 0; } function answerCorrect(questionNumber, answer) { // declare a variable to hold return value var correct = false; //if ansa provided is same as ansa then correct ansa is true if (answer == answers[questionNumber]) { numberOfQuestionsCorrect++; correct = true; } // return whether the ansa was correct (true or false) return correct; } function getQuestion() { if (questions.length != numberOfQuestionsAsked) { var questionNumber = Math.floor(Math.random() * questions.length) while (questionsAsked[questionNumber] == true) { questionNumber = Math.floor(Math.random() * questions.length); } var questionLength = questions[questionNumber].length; var questionChoice; numberOfQuestionsAsked++; var questionHTML = "<h4>Question " + numberofQuestionAsked + "</h4>"; questionHTML = questionHTML + "<p>" + questions[questionNumber][0]; questionHTML = questionHTML + "</p>; for (questionChoice = 1;questionChoice < questionLength;questionChoice++) { questionHTML = questionHTML + "<input type=radio " questionHTML = questionHTML + " name=radQuestionChoice" if (questionChoice == 1) { questionHTML = questionHTML + " checked"; } questionHTML = questionHTML + ">" + questions[questionNumber][questionChoice]; questionHTML = questionHTML + "<br>" } questionHTML = questionHTML + "<br><input type= 'button'" questionHTML = questionHTML + " value='Answer Question'"; questionHTML = questionHTML + "name=buttonNextQ "; questionHTML = questionHTML + "onclick='return buttonCheckQ_onclick()'>"; currentQNumber = questionNumber; questionsAsked[questionNumber] = true; } else { var questionHTML = "<h3>Quiz Complete</h3>"; questionHTML = questionHTML + "You got " + numberOfQuestionsCorrect; questionHTML = questionHTML + " questions correct out of " questionHTML = questionHTML + " numberOfQuestionsAsked; questionHTML = questionHTML + "<br><br>Your rating is " switch(Math.round(((numberOfQuestionsCorrect / numberOfQuestionsAsked) * 10))) { case 0: case 1: case 2: case 3: questionHTML = questionHTML + "Try next time"; break; case 4: case 5: case 6: case 7: questionHTML = questionHTML + "Average"; break; default: questionHTML = questionHTML + "Excellent" } questionHTML = questionHTML + "<br><br><A " questionHTML = questionHTML + "href= 'Exampage.htm'><Strong>" questionHTML = questionHTML + "Start again</strong></A>" } return questionHTML; } </script> </head> <body> </body> </html> thnks in advance hello everyone, first a confession-i have a very VERY superficial understanding of javascript and other programing languages. i am a teacher, preparing a small quiz that my students can take online. i found a free script code on the net, but there's a small problem - i want to give marks for every correct answer in the quiz but penalize for every incorrect answer. the ready-made code already gives marks for the correct answer, but does not penalize the incorrect answer. the part of the code is as under code begins.... Code: function gradeit(){ var incorrect=null for (q=1;q<=totalquestions;q++){ var thequestion=eval("document.myquiz.question"+q) for (c=0;c<thequestion.length;c++){ if (thequestion[c].checked==true) actualchoices[q]=thequestion[c].value } if (actualchoices[q]!=correctchoices[q]){ //process an incorrect choice if (incorrect==null) incorrect=q else incorrect+="/"+q } } if (incorrect==null) incorrect="a/b" document.cookie='q='+incorrect if (document.cookie=='') alert("Your browser does not accept cookies. Please adjust your browser settings.") else window.location="results.htm" } ...code ends many thanks in advance. -mdb |