WebReference.com - Drawing Charts with JavaScript (6/7) | WebReference

WebReference.com - Drawing Charts with JavaScript (6/7)

To page 1To page 2To page 3To page 4To page 5current pageTo page 7
[previous] [next]

Drawing Charts with JavaScript

Letting the user add data to chart

We'll now add two text boxes and a button to our form, allowing the user to enter student names and their respective scores. We'll only need to add one function to our script -- addNewStudent() -- which places the new student along with her score into the appropriate arrays, and creates a new Option in our Select element. First, of course, it validates the entries, to ensure that a number was entered in the score field and that the name field is not empty. I've left the original arrays, arStudents and arScores pre-populated, but there is no reason to do so. We could initialize these as empty arrays and allow the end user to enter all of the data if we so choose. Here's the relevant HTML:

<input name=student type=text size=12>
<input name=score type=text size=12>
<input type=button value="Add Student" onclick="addNewStudent()">

And here is the new function:

function addNewStudent() {
  if(whichItem==0)
      return // make sure they don't select the empty element
  newStudent = document.chartForm.student.value;
  newScore = document.chartForm.score.value;
  // now validate the input
  if(newStudent.length < 1) {
     alert("You must enter a name.");
	 document.chartForm.student.focus();
	 return;
  }
  newScore = parseInt(newScore);
  if(isNaN(newScore)) {  // make sure it's a number
     alert("Please Enter a numerical value for this student");
	 document.chartForm.score.focus();
	 return;
  }
  // if we get here, add the student & score to the arrays
  // and add a new Option to the Select element
  arStudents[arStudents.length] = newStudent;
  arScores[arScores.length] = newScore;
  document.chartForm.chartItems.options[document.chartForm.chartItems.options.length]=new Option(newStudent+" "+newScore);
  // clear the text entry fields
  document.chartForm.reset();
  // now reset maxWidth in case we have a larger value
  for(i=0; i < arScores.length; i++) {
     if(arScores[i] > maxWidth)
        maxWidth = arScores[i];
  }
  return;
}

Adding new elements to an array should be old hat by now, so no further discussion should be necessary for the above function. Let's try out our new interactive form. We can add a new student to the drop down list at will, and we can chart our students and their scores. We can even switch back and forth between charting and adding new students to select from. Give it a go:

Add Student to List
Name  
Score

Choose students to chart:

 
 
 
 
 
 
 
 
 
 

Let's wrap it up with a look at the entire script.


To page 1To page 2To page 3To page 4To page 5current pageTo page 7
[previous] [next]

Created: March 6, 2002
Revised: March 6, 2002

URL: https://webreference.com/programming/javascript/charts/6.html