?
Solved

total up scores in javascript

Posted on 2005-04-16
8
Medium Priority
?
482 Views
Last Modified: 2010-05-18
i was given a piece of code to insert into the page but i don't know where to insert it. Can you help me ?

here is the code i was given
function totalQuiz() {
  var total = 0;
  for (i=0;i<quiz.length;i++) total+= quiz[i].score;
  return total
}

and then insert this peice of code somewhere as well

your current total =
<script>
 totalQuiz()
</script>

Here are the 2 scripts that i will be using

this is the summary page where i want the total of the test to be displayed.
<HTML>
<HEAD>
<TITLE>Untitled Document</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
// Make copy of quiz object from navigation bar at load time.
var quiz = parent.nav.quiz

// Functions that provide quiz-related data to be dynamically written
// to the summary page

// Returns the width of a bar graph image for a question time limit
function getMaxImg(i) {
  return quiz[i].timeLimit * 3
}

// Returns the width of a bar graph image for a question actual time
function getActImg(i) {
  return quiz[i].time * 3
}

// Returns the question time limit for display after the bar graph
function getMax(i) {
  return "<FONT SIZE='-1'>" + quiz[i].timeLimit + "</FONT>"
}

// Returns the question actual time for display after the bar graph
function getAct(i) {
    if (quiz[i].time <= quiz[i].timeLimit) {
      return "<FONT SIZE='-1'>" + quiz[i].time + "</FONT>"
    } else {
    // if actual time exceeds the time limit, the knowledge
    // object does not increment the actual time past
    // the time limit + 1.
      return "<FONT SIZE='-1'>" + quiz[i].time + " (or more)</FONT>"
  }
  return "n/a"
}

// Returns the question number of tries recorded by the knowledge object
function getTries(i) {
  return quiz[i].tries
}

// Returns the question score recorded by the knowledge object
function getScore(i) {
  var triesResult, timeResult, scoreResult
  with (quiz[i]) {
    triesResult = tries
     timeResult = time
     scoreResult = score
  }
  return scoreResult // 100 - (triesResult * timeResult)
}
//-->
</SCRIPT>
<script language="JavaScript" src="scripts/behActions.js"></script>
<script language="JavaScript" src="scripts/behCourseBuilder.js"></script>
<script language="JavaScript" src="scripts/interactionClass.js"></script>
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
//-->
</script>
</HEAD>

<BODY BGCOLOR="#E2E3DE" onLoad="MM_initInteractions()">
<H1><font face="Arial, Helvetica, sans-serif" size="4">Test Results</font></H1>
<P><font face="Arial, Helvetica, sans-serif" size="2">Here are the results of
  your test. For each question, you can see how well you did against the clock.
  The yellow bar (<IMG SRC="images_dg/chartYellow.gif" WIDTH="10" HEIGHT="10">)
  shows the allowable time period for the question in seconds; the orange bar
  (<IMG SRC="images_dg/chartOrange.gif" WIDTH="10" HEIGHT="10">) shows your actual
  time. Can you do better next time?</font></P>
<TABLE BORDER="1" WIDTH="48%" ALIGN="CENTER">
  <TR>
    <TH width="26%" BGCOLOR="#E2E3DE"><font face="Arial, Helvetica, sans-serif" size="2">Question
      No.</font></TH>
    <TH width="38%" BGCOLOR="#E2E3DE"><font face="Arial, Helvetica, sans-serif" size="2">Time</font></TH>
    <TH width="14%" BGCOLOR="#E2E3DE"><font face="Arial, Helvetica, sans-serif" size="2">Tries</font></TH>
    <TH width="22%" BGCOLOR="#E2E3DE"><font face="Arial, Helvetica, sans-serif" size="2">Score</font></TH>
  </TR>
  <SCRIPT LANGUAGE="JAVASCRIPT">
  if (!quiz) {
    setTimeout("location.reload(true)", 2000)
  } else {
  var pageCounter = 0
  for (var i = 0; i < quiz.length; i++) {
      if (i > 0 && i < (quiz.length - 1)) {
        document.writeln("<TR>")
        document.writeln("<TD ALIGN='CENTER'>" + ++pageCounter + "</TD>")
        document.writeln("<TD><IMG SRC='images_dg/chartYellow.gif' WIDTH='"+ getMaxImg(i) + "' HEIGHT='12' HSPACE='2' VSPACE='2' ALIGN='baseline'>" + getMax(i) + "<BR>")
        document.writeln("<IMG SRC='images_dg/chartOrange.gif' WIDTH='"+ getActImg(i) + "' HEIGHT='12' HSPACE='2' VSPACE='2'>" + getAct(i))
        document.writeln("</TD>")
        document.writeln("<TD ALIGN='CENTER'>" + getTries(i) + "</TD>")
        document.writeln("<TD ALIGN='CENTER'>" + getScore(i) + "</TD>")
        document.writeln("</TR>")
      }
    }
  }
  </SCRIPT>
  </TABLE>


<interaction name="ActionMgr01" object="G01" template="080_Action Manager/010_ActionMgr_03.agt" includesrc="interactionClass.js">
<div name="G01Layer">
  <form name="G01controls">
  </form>
</div>
<script language="JavaScript">
<!--
  // Copyright 1998,1999 Macromedia, Inc. All rights reserved.
  function newG01() {
    G01 = new MM_interaction('G01',0,0,0,null,0,0,0,'','','','',0);
    G01.init();
    G01.am('segm','Total_score_',1,0);
  }
  if (window.newG01 == null) window.newG01 = newG01;
  if (!window.MM_initIntFns) window.MM_initIntFns = ''; window.MM_initIntFns += 'newG01();';
//-->
</script>
<cbi-select object="G01"></interaction>
<form name="form1" method="post" action="">
  <strong>Total:</strong>
  <input name="textfield" type="text" size="6">
</form>
<p>&nbsp;</p>
<FORM>
  <P>&nbsp;</P>
</FORM>

<p>&nbsp;</p>
</BODY>
</HTML>


here is code for the nav page where the scores are passed on to the summary page.

<html>
<head>
<BODY BGCOLOR="#E2E3DE" onLoad="MM_initInteractions()">
<title>Navigation</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language='JavaScript'></script>
<script language='JavaScript' src='scripts/interactionClass.js'></script>
<script language='JavaScript' src='scripts/elemHotaClass.js'></script>
<script language='JavaScript' src='scripts/behDragLayer.js'></script>
<script language='JavaScript' src='scripts/behCourseBuilder.js'></script>
<script language='JavaScript' src='scripts/behActions.js'></script>
</head>
<body bgcolor="#FFFFFF" onLoad="MM_initInteractions()">
<script language="javascript">
<!--
// constructor for a quiz page object
function quizPage(src,time, timeLimit, tries, score, completed) {
  this.src = src
  this.time = (!time) ? 0 : time
  this.timeLimit = (!timeLimit) ? 0 : timeLimit
  this.tries = (!tries) ? 0 : tries
  this.score = (!score) ? 0 : score
  this.completed = (!completed) ? false : completed
}

// create array of all quiz pages in the entire quiz
var quiz = new Array()

/* ----------------------------------------------------------------
   MODIFY THE CODE IN THE FOLLOWING SECTION.
   This is where you define the parameters for each page of the
   quiz, including introductory and summary pages.
   
   Create a new entry in the quiz array by assigning a new
   quizPage object to succeeding quiz array entries (starting with
   zero). Parameters that must be set for the initial objects describe
   the URL of the top frame page.
   ------------------------------------------------------------------ */
quiz[0] = new quizPage("multi_page_quiz_overview.htm")
quiz[1] = new quizPage("multi_page_quiz_question1.htm")
quiz[2] = new quizPage("multi_page_quiz_question2.htm")
quiz[3] = new quizPage("multi_page_quiz_question3.htm")
quiz[4] = new quizPage("multi_page_quiz_question4.htm")
quiz[5] = new quizPage("multi_page_quiz_question5.htm")
quiz[6] = new quizPage("multi_page_quiz_question6.htm")
quiz[7] = new quizPage("multi_page_quiz_question7.htm")
quiz[8] = new quizPage("multi_page_quiz_question8.htm")
quiz[9] = new quizPage("multi_page_quiz_question9.htm")
quiz[10] = new quizPage("multi_page_quiz_question10.htm")
quiz[11] = new quizPage("multi_page_quiz_question11.htm")
quiz[12] = new quizPage("multi_page_quiz_question12.htm")
quiz[13] = new quizPage("multi_page_quiz_question13.htm")
quiz[14] = new quizPage("multi_page_quiz_question14.htm")
quiz[15] = new quizPage("multi_page_quiz_question15.htm")
quiz[16] = new quizPage("multi_page_quiz_question16.htm")
quiz[17] = new quizPage("multi_page_quiz_question17.htm")
quiz[18] = new quizPage("multi_page_quiz_question18.htm")
quiz[19] = new quizPage("multi_page_quiz_question19.htm")
quiz[20] = new quizPage("multi_page_quiz_question20.htm")
quiz[21] = new quizPage("multi_page_quiz_question21.htm")
quiz[22] = new quizPage("multi_page_quiz_question22.htm")
quiz[23] = new quizPage("multi_page_quiz_question23.htm")
quiz[24] = new quizPage("multi_page_quiz_question24.htm")
quiz[25] = new quizPage("multi_page_quiz_question25.htm")
quiz[26] = new quizPage("multi_page_quiz_question2b.htm")
quiz[27] = new quizPage("multi_page_quiz_summary4.htm")


/* -----------------------------------------------------------------
   END CODE MODIFICATION SECTION
   -----------------------------------------------------------------*/
   
// navigate to next quiz page in sequence
function goNext() {
  var currPage, i
  for (i=0; i<(quiz.length-1); i++) {
    if (parent.main.location.href.indexOf(quiz[i].src) != -1) {
       parent.main.location.href = quiz[i+1].src
       break
     }
  }
}

// navigate to previous quiz page in sequence
function goPrev() {
  var currPage, i
  for (i=(quiz.length-1); i>0; i--) {
    if (parent.main.location.href.indexOf(quiz[i].src) != -1) {
       parent.main.location.href = quiz[i-1].src
       break
     }
  }
}

// navigate to first quiz page in sequence
function goFirst() {
  parent.main.location.href = quiz[0].src
}

// navigate to first quiz page in sequence
function goLast() {
  parent.main.location.href = quiz[quiz.length-1].src
}

// don't go anywhere, but set visibility of navigation control
// layers in the event of a page reload
function initPage() {
  var i, storage
  storage = document.forms["persistence"].persist.value
  if (storage) {
    restoreQuizObjects(storage)
  }
  for (i=0; i<(quiz.length); i++) {
    if (parent.main.location.href.indexOf(quiz[i].src) != -1) {
       break
     }
  }
}

// event handler for Navigator frame resize/reload
function handleNNResize() {
  var NS = (navigator.appName.indexOf("Netscape") != -1)
  if (NS) {
     history.go(0)
  }
}

// restoration of data from persistent storage
// using a text field in the nav frame for storage
function restoreQuizObjects(storage) {
  var quizzes, p
  quizzes = storage.split(":")
  for (var i = 0; i < quizzes.length-1; i++) {
    if (quizzes[i]) {
       p = quizzes[i].split(",")
       quiz[i] = new quizPage(p[0], p[1], p[2], p[3], p[4], parseInt(p[5]),
                              parseInt(p[6]), parseInt(p[7]), parseInt(p[8]), p[9])
     }
  }
  saveQuizObjects()
}

// saving quiz object data in persistent storage
// using a text field in the nav frame for storage
function saveQuizObjects() {
  var oneQuiz = new Array(), storage = ""
  for (var i = 0; i < quiz.length; i++) {
       for (j in quiz[i]) {
       oneQuiz[oneQuiz.length] = quiz[i][j]
     }
    storage += (oneQuiz) ? oneQuiz.join() + ":" : ""
     oneQuiz.length = 0
  }
  if (document.forms["persistence"]) {
    document.forms["persistence"].persist.value = storage
  }
}

// pass along value of KO tries to quiz page object
function setTries(URL, tries) {
  var obj = findPage(URL)
  obj.tries = tries
  if (document.forms["triesForm"]) {
    document.forms["triesForm"].tries.value = obj.tries
  }
  saveQuizObjects()
}

// set completed property of a quiz object
function setAsDone(URL) {
  var obj = findPage(URL)
  obj.completed = true
  saveQuizObjects()
}

// pass along values of time and time left to quiz page object
function setTimes(URL, time, timeLimit) {
  var obj = findPage(URL)
  obj.time = time
  obj.timeLimit = timeLimit
  saveQuizObjects()
}

// pass along values of score to quiz page object
function setScores(URL, score) {
  var obj = findPage(URL)
  obj.score = score
  saveQuizObjects()
}
// reset tries and score property settings for a quiz object
function resetObject(URL) {
  var obj = findPage(URL)
  obj.tries = 0
  var triesFld = MM_intFindObject("tries")
  triesFld.value = obj.score
  saveQuizObjects()
}
// locate the quiz object for a given quiz URL
// (invoked by init() function of each quiz page)
function findPage(URL) {
  var currPage, i
  for (i=0; i<(quiz.length); i++) {
    if (URL.indexOf(quiz[i].src) != -1) {
       return quiz[i]
     }
  }
  return quiz[0]
}
//-->
</script>
<interaction object="G01" name="navigation" template="003_Explore\001_explore_random_04.agt" includesrc="interactionClass.js,elemHotaClass.js,behDragLayer.js">
<div name="G01Layer"> <!-- Copyright 1998 Macromedia, Inc. All rights reserved. -->
  <span name="G01question"> </span> </div>
<div id="G01First" style="position:absolute; left:8px; top:14px; width:65px; height:65px; z-index:2; visibility: visible">
  <img name="G01FirstImg" src="RESTART.GIF"></div>
<div id="G01Previous" style="position:absolute; left:76px; top:14px; width:65px; height:65px; z-index:2; visibility: visible">
  <img name="G01PreviousImg" src="PREVIOUS.GIF"></div>
<div id="G01Next" style="position:absolute; left:144px; top:14px; width:65px; height:65px; z-index:2; visibility: visible">
  <img name="G01NextImg" src="NEXT.GIF"></div>
<div id="G01Score" style="position:absolute; left:212px; top:14px; width:65px; height:65px; z-index:2; visibility: visible">
  <img name="G01ScoreImg" src="FINISH.GIF"></div>
<script language="JavaScript">
<!--
  function newG01() {
    G01 = new MM_interaction('G01',1,0,0,null,0,0,0,'','','c','',0);
    G01.add('hota','First',0,1,null,0);
    G01.add('hota','Previous',0,1,null,0);
    G01.add('hota','Next',0,1,null,0);
    G01.add('hota','Score',0,1,null,0);
    G01.init();
    G01.am('segm','Check Time_',1,0);
    G01.am('cond','At Time Limit_','G01.timeAtLimit == true',0);
    G01.am('actn','Popup Message','MM_popupMsg(\'You are out of time\')','pm');
    G01.am('actn','Set Interaction Properties: Disable Interaction','MM_setIntProps(\'G01.setDisabled(true);\')','sp');
    G01.am('end');
    G01.am('segm','First Feedback_',1,0);
    G01.am('cond','First Selected_','G01.e[\'First\'].selected == true',0);
     G01.am('actn','Call JavaScript','MM_callJS(\'goFirst()\')','cjs');
    G01.am('end');
    G01.am('segm','Previous Feedback_',1,0);
    G01.am('cond','Previous Selected_','G01.e[\'Previous\'].selected == true',0);
    G01.am('actn','Call JavaScript','MM_callJS(\'goPrev()\')','cjs');
     G01.am('end');
    G01.am('segm','Next Feedback_',1,0);
    G01.am('cond','Next Selected_','G01.e[\'Next\'].selected == true',0);
    G01.am('actn','Call JavaScript','MM_callJS(\'goNext()\')','cjs');
     G01.am('end');
    G01.am('segm','Score Feedback',1,0);
    G01.am('cond','Score Selected','G01.e[\'Score\'].selected',0);
    G01.am('actn','Call JavaScript','MM_callJS(\'goLast()\')','cjs');
    G01.am('end');
    G01.am('segm','Correct Handling_',1,0);
    G01.am('cond','Interaction is Correct_','G01.correct == true',0);
    G01.am('actn','Popup Message','MM_popupMsg(\'You got it!\')','pm');
    G01.am('actn','Set Interaction Properties: Disable Interaction','MM_setIntProps(\'G01.setDisabled(true);\')','sp');
    G01.am('end');
    G01.am('segm','Incorrect Handling_',1,0);
    G01.am('cond','Interaction is Incorrect_','G01.correct == false',0);
    G01.am('end');
    G01.am('segm','Handle all other clicks_',1,0);
    G01.am('cond','Unknown Response_','G01.knownResponse == false',0);
    G01.am('actn','Popup Message','MM_popupMsg(\'Select a hot area to see if you are right.\')','pm');
    G01.am('end');
    G01.am('segm','Check Tries_',1,0);
    G01.am('cond','Tries Exceeded_','G01.triesAtLimit == true',0);
    G01.am('actn','Popup Message','MM_popupMsg(\'That was the last attempt allowed.\')','pm');
    G01.am('actn','Set Interaction Properties: Disable Interaction','MM_setIntProps(\'G01.setDisabled(true);\')','sp');
    G01.am('end');
  }
  if (window.newG01 == null) window.newG01 = newG01;
  if (!window.MM_initIntFns) window.MM_initIntFns = ''; window.MM_initIntFns += 'newG01();';
//-->
</script>
<cbi-select object="G01"></interaction>
<DIV ID="triesLayer" STYLE="position:absolute; width:247px; height:52px; z-index:3; left: 9px; top: 5px; visibility: hidden">
  <FORM NAME="persistence" METHOD="post" ACTION="">
    <BR>
    <INPUT TYPE="text" NAME="persist" SIZE="80">
  </FORM>
  <FORM NAME="triesForm" METHOD="post" ACTION="">
    Number of tries for this question:
    <INPUT TYPE="text" NAME="tries" SIZE="4" VALUE="0">
  </FORM>
</DIV>
</body>
</html>


Your help is greatly appriciated
0
Comment
Question by:act1ve
  • 4
  • 4
8 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 13796851
Insert
function totalQuiz() {
  var total = 0;
  for (i=0;i<quiz.length;i++) total+= quiz[i].score;
  return total
}
anywhere inside the script tags

and the second code anywhere you want the score printet out
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 13796857
I have commented in the original question and will ask this to be deleted and the points refunded.
I am sorry I missed the question in the original
0
 

Author Comment

by:act1ve
ID: 13796867
1. Do i insert the Function total Quiz code in the nav script or the summary script where the total is going to be displayed

2. do i insert
       <script>
         totalQuiz()
         </script>
 inside a textfield.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 2000 total points
ID: 13796885
The function can be put anywhere inside the script tags on the page

the totalQuiz() has to be called on an event.
For example on page load or when a form is submitted.

You have not shown me a textfield anywhere.

When do you want the quiz totalled and where?
Where is your php script called
0
 

Author Comment

by:act1ve
ID: 13796901
the textfield is at the bottom of the summary page

<form name="form1" method="post" action="">
  <strong>Total:</strong>
  <input name="textfield" type="text" size="6">
</form>
<p>&nbsp;</p>
<FORM>
  <P>&nbsp;</P>
</FORM>

Can the testQuiz()  be inserted into the textfield with a submit button to sent the total to a database.

i have started with the PHP to send the total to the database
 
0
 

Author Comment

by:act1ve
ID: 13796906
Is sending the total to the database the same as sending a username to the database
0
 

Author Comment

by:act1ve
ID: 13796920
I tried inserting the totalQuiz()inthe testfield part like this

<form name="form1" method="post" action="">
  <strong>Total:</strong>
  <script>
  totalQuiz()
  </script>
  <input name="total" type="text" readonly size="6">
</form>

but it is still not displaying anyting
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 13797067
Either (if you do not need to see it except on the server

<form name="form1" method="post" action="" onSubmit="this.total.value=totalQuiz()">
  <strong>Total:</strong>
  <input name="total" type="text" readonly size="6">
</form>

or
<form name="form1" method="post" action="">
  <strong>Total:</strong>
  <input name="total" type="text" readonly size="6">
</form>


  <script>
document.form1.total.value=totalQuiz()  
  </script>

e.g. after the end of the form

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question