HTML Help Forum HTML Help
Please Search for the answer to your question before asking it! Thanks.
 

Issue with arrays in JavaScript
Post a Reply to this Topic Ask a New Question
Click here to go to the original topic
       HTML Help Forum -> Javascript
View previous topic :: View next topic  
Author Message
penguinJack



Joined: 18 Dec 2008
Posts: 3

Posted: Thu Dec 18, 2008 9:30 am     Issue with arrays in JavaScript  

I basically have this question that i need to answer but haven't been given the resources to help me out. If anyone could offer me some guidance i'd be very appreciative.
A society is to hold an election to choose their honorary secretary. Five candidates have been nominated and the following postal votes have already been received and counted:
cand1 – 230; cand2 – 341; cand3 – 196; cand4 – 81; cand5 – 257
The votes cast at the meeting are to be added to the postal votes and the winner is the candidate with the most votes. The result is to be declared in the format shown in Figure 2.

Total membership: 3000. Total votes cast: 2537.

cand1 ....... votes: 1030 ......% of total vote: 40.6........% of membership: 34.33
cand2 ....... votes: 466 ........% of total vote: 18.37......% of membership: 15.53
cand3 ....... votes: 434 ........% of total vote: 17.11......% of membership: 14.47
cand4 ....... votes: 100 ........% of total vote: 3.94........% of membership: 3.33
cand5 ....... votes: 507 ........% of total vote: 19.98......% of membership: 16.9
Winner is cand1 with 1030 votes

Figure 2 The format in which the result is to be displayed
A program is to be written to perform the calculations, according to the following task description:
1 The program should have three variables: candidateArray, totalMembership, and totalVotes. The variable candidateArray is an array used to store the votes for each candidate. When it is declared it should be initialised with the results of the postal votes, as given earlier.
2 The program should start by asking the user to input the number of members in the society. Here and in step 3 below you can assume that the user will always input a valid number when requested to do so.
3 It should then ask the user to input the number of votes cast at the meeting for each candidate, using the prompt message ‘Please enter the votes cast for candidate n’ (where n stands for the number of the candidate – it will successively take the values 1, 2, 3, etc). Your program does not need to check these numbers in any way.
4
The program should finally produce the required output in approximately the format shown in Figure 2. Note that the lines will be ragged if, as shown, there are differences in the number of digits in some of the values, so the columns will not always line up as neatly as those in Figure 2. You may assume that there will not be a tie for first place.
(iii) Code the above program in JavaScript, following the style guidance of Question 2. Do not spend a lot of time trying to line up the columns in the output – a reasonable approximation, similar to that in Figure 2, will be quite adequate.
Straystudio



Joined: 14 Apr 2008
Posts: 297
Location: Nord Italy

Posted: Sat Dec 20, 2008 4:41 am     AxB /100 = C is the B% of A => Cx100/A gives B which % is  

As for how displaying output, it would not be so difficult to keep everything well columned in TABLE cells, I want to feel myself pretty handy with.
JavaScript can change either the whole TD content directly via .innerHTML
or what to be displayed in an INPUT TYPE="Text" textbox via .value
textboxes still being contained inside TD table cells.

Another way would be doing a simple in-line mix of bare text parts with textboxes; INPUT does act as an in-line Element, indeed.

I'll be running a third way, with a single long-sized text field printing as unbroken the whole pattern-row You gave.


This just to have a clue, a starting point; it won't be anything definitive.
An Array starts counting by zero, so cand[0] being the first item of the Array would return data for cand1; it is possible to leave it empty (available), though to have easier a correspondence.
Code:
<html>
<head>
<title>election test 01
        </title>
    <script type="text/javascript">

var totalMembership = "--";

var cand = new Array();
cand[0] = "   " ;
cand[1] = "230" ;
cand[2] = "341" ;

function revise(){
 totalMembership = prompt('Please enter the number of members in the society (total membership)', '');
 document.getElementById("members").value = ' '+totalMembership;
 }


function compute(where, who){

 var meetingVotes = prompt('Please enter the votes cast for candidate  '+who+'', '');

 var votes = cand[who]*1+meetingVotes*1;
 var totPerc = votes*100/totalMembership;
 document.getElementById(where).value=' '+who+'....... votes: '+votes+' ......% of membership: '+totPerc+'';
 }

</script>


</head>
<body>

<b>Total membership:</b> <input id="members" type="text" size="6" readonly>&nbsp;<input
                          type="button" value="revise" onclick="revise()"><br>
<br>
<input id="field1" type="text" size="100" readonly><input type="button" value="ENTER" onclick="compute('field1', 1)"><br>
<input id="field2" type="text" size="100" readonly><input type="button" value="ENTER" onclick="compute('field2', 2)"><br>

</body>
</html>



Math.round()
==========
Notice You may get pretty long decimals up to 15 digits printed out by the computer, depending on which values combine.

So, a good improvement to think to deal with, is IS native function Math.round() rounding a number to the nearest integer.
The trick to multiply by 100 the number-with-decimals to be rounded, while it has still to be taken under Math.round, then dividing its result back by 100, works out great a method to round to the first two decimal digits. In a few words, the decimal point goes temporarily moved ahead by multipling by 100 (* sign in JS), at the last reforming a decimal number by the division.

As a result on Your field:
var totPerc = Math.round( votes*100/totalMembership *100) /100;


How to ensure that the User firstly enters the current number of members in the society.
=================================================================
I would avoid a prompt automatically popping-up as soon as page loads.

Here one more variable has been added, as set as false by default; the User going through revise() function, only turns it into being true.

var revision = false;

function revise(){
totalMembership = prompt('Please enter the number of members in the society (total membership)', '');
document.getElementById("members").value = ' '+totalMembership;
revision= true;
document.getElementById("reviseBtn").disabled = true; //requires id with the button
}


function compute(where, who){
if(revision==true){
var meetingVotes = prompt('Please enter the votes cast for candidate '+who+'', '');

var votes = cand[who]*1+meetingVotes*1;
var totPerc = Math.round(votes*100/totalMembership*100)/100;
document.getElementById(where).value=' '+who+'....... votes: '+votes+' ......% of membership: '+totPerc+'';
} else {
alert('Please, confirm or revise "Total membership" amount, before.');
revise();
}
}

if/else statements.
==============
What compute() function was originally designed to do, only if revise() function has been previuosly triggered, it can be executed, now thanks to an if(hypothesis) {instruction} statement conditioning the function.

Do not forget to assign the "revise" button id="reviseBtn" in the BODY, as
document.getElementById("reviseBtn").disabled = true;
wants to disable it as soon as the thing is done; to avoid any further value to be entered in error there once process is on its way.


var totalMembership could have even a default value (say, "3000") a simple function can deliver to the input id="members" field on body onloading;
declaring :
var totalMembership = "3000";

then :
function setup(){
document.getElementById("members").value = ' '+totalMembership;
}
called by :
<body onload="setup();">

and also :
totalMembership = prompt('message', ''+totalMembership+'');
displaying in the prompt. Message changes accordingly (enter or confirm/revise).


var totalVotes = "?"; // How to work out how many "Total votes cast" are.
=======================================================
As for calculating percentuage on the "Total votes cast" I intentionally omitted for clarity at first, well it figures out a number which only after having entered and summed all the votes, it can be obtained.
If We won't enter each candidate 's votes twice, the first time to works out a value for the var totalVotes, the second taking it in calculation likewise done with var totalMembership, well We need to store them (votes) somewhere on the first (and single) time User enters them.
More INPUT fields could enter in play to do that, TYPE="Hidden", even though.

I'll be submitting a SCRIPT where a virtual further Array gets automatically compiled, instead.


.
 
 
DARFUR
HOSTING / DESIGN
MAKE MONEY

       HTML Help Forum -> Javascript
Page 1 of 1


Powered by phpBB Search Engine Indexer
Powered by phpBB 2.0.19 © 2001, 2002 phpBB Group