The window.prompt method returns a string when the user enters something, or null if the user enters nothing. You should also check that the number entered is a valid number. Try this code below:
PHP Code:
var totalMembership = 0;
var totalVotes = 0;
var candidateArray = [230, 341, 196, 81, 257];
var candidateLen = candidateArray.length;
function calcVotes() {
var i = 0;
var votes = 0;
totalMembership = promptValidNumber("Please enter the number of members", "",
"Please enter a valid number of members");
for(i; i < candidateLen; i++) {
votes = promptValidNumber("enter votes cast for candidate " + (i+1), "",
"Please enter a valid number of votes.");
candidateArray[i] += votes;
}
}
function promptValidNumber(promptStr, promptVal, errorStr) {
var n = null;
promptVal = promptVal || "";
errorStr = errorStr || "Please enter a valid number.";
while ( isNaN(n = Number(prompt(promptStr, promptVal))) ) {
alert(errorStr);
}
return n;
}
Bookmarks