Issues writing promt dialogue data to an array

Discussion in 'JavaScript' started by Chronia, Aug 1, 2009.

  1. #1
    Hi there,

    I'm fairly new at JavaScript, and am still learning alot. I have an assignment for school that I am completely stumped on. The purpose of it is to calculate the gross pay of 3 employees by gathering the information using prompt dialogue boxes. I also have to calculate overtime (I haven't written the coding for this yet) if the employee has worked over 40 hours.

    Anyways, the problem I am having is that when the data is entered by the user in the prompt boxes it won't store the first value (name) in the name array, however it will store the other values (hours and payRate) in the corresponding arrays. Theoretically the coding should be the same yet, when the program is run using an onlclick command via a form button, the values that should be stored in the name array (indexes 0-2) are "undefined". I can't understand why.

    I am allowed to ask for help for this assignment, provided I am not given the "answers" so what I am asking for here is some general information, perhaps a pointer in the direction that my error may lay, or even a typed explanation is fine, just so long as I am not given coding (other my own coding sited as an example when giving a typed explanation).

    Here is what I have for my javascript coding, the HTML really isn't important as the only Javascript is the call of the calcPay function in the onclick even handler for the form button, so I won't post my HTML coding, just the JavaScript. My coding is a embedded script placed with in the head element of the document. Thanks so much in advance for any help I can get with this!

    ______________________________

    <script type= "text/javascript">

    name = new Array(3);
    payRate = new Array(3);
    hours = new Array(3);
    grossPay = new Array(3);

    function calcPay() {
    getInfo();
    document.write ("<h1>Employee Gross Pay Totals</h1><hr />");
    for (j=0; j <= name.length; j++) {
    document.write("<b>Employee Name: </b>" + name[j] + "<br />");
    document.write("<b>Total Hours Worked: </b>" + hours[j] + "<br />");
    document.write("<b>Hourly Pay Rate: </b>" + payRate[j] + "<br />");

    /* insert code statements to calculate hourly pay and overtime pay to equal gross pay */

    }
    }

    function getInfo() {
    for (i=0; i<= name.length; i++) { /*name.length used instead of hours or payRate as, theoretically, length of payRate and hours arrays should not be longer than than the total amount of employees (name) */

    name = prompt("Enter Name of Employee: ", "");
    payRate = prompt("Enter the Hourly Rate of Pay for " + name +" (do not enter currency sign)", "");
    hours = prompt("Enter the number of Hours worked by " + name + " last week:", "");
    }


    }


    </script>
     
    Last edited: Aug 1, 2009
    Chronia, Aug 1, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    a few pointers...

    first of all - using the array constructor to instigate an array with a set length is not practical at all. define the array loose in the sense of:

    var arrayName = [], arrayname2 = [];

    you can't always know how many elements an array will have...

    another thing. get into the habit of using "var" and telling the difference between a local and a global variable scope. google for it.

    
    <script>
    var foo = 1;
    
    function bar() {
        foo = 2; // will change global scope
    }
    
    alert(foo); // 1
    bar();
    alert(foo); // 2
    
    function barbar() {
        var foo = 3; // local scope, global is unchanged
    }
    
    barbar();
    alert(foo); // still 2.
    </script>
    
    PHP:
    another thing and probably the reason why your code fails - namespacing is pretty awkward in javascript. take PHP for instance - you cannot overwrite anything that's predefined - functions, constants etc - they are set. not so in javascript - you can literally rewrite the whole thing. for example, you can replace the alert() function with something like this: var alert = function() { return false; }; - and all code that alerts anything will now silently dismiss.

    this can be very useful when prototyping / extending functionality - but it also means you can accidentally overwrite or reference things you should not. in your original code, you have called your array 'name' which is a special keyword / attribute and reserved in IE (same as id, class etc). AVOID naming your variables like so - to be safe, use a more explicit naming convention like customerName or sName (string Name) etc - be creative.

    Another thing. javascript supports objects called JSON - JS object notation. it's a great invention that allows you to group data together and treat it as an object or an array.

    for example:
    
    var employee = {
        age: 45,
        sex: "male",
        "hair colour": "blonde",
        rate: 27.50,
        name: "bob robertson",
        init: function() {
            alert(this.name);
        }
    };
    
    // referencing:
    alert(employee.age); // as object property
    alert(employee['age']); // as array
    alert(employee['hair colour']); // when having a space in the property, referece as object won't work so we do as array only.
    
    employee.init();  // alerts bob robertson.
    
    PHP:
    this negates the need to run 4 arrays in parallel - just create one with the right properties, far easier to manage and iterate after.

    finally - install www.getfirebug.com on firefox and use console.log(object) / console.info(object) to debug/output what you need. NEVER use document.write, really bad practice, slows down page execution like shitloads.

    anyway, consider this code and take it from there (done in a hurry but you get the idea):
    http://fragged.org/dev/DP-calcPay.php
    <html>
    <body>
    <div id="output"></div>
    <script type="text/javascript">
    var employees = [], targetDiv = document.getElementById("output"), calcPay = function(howMany) {
        targetDiv.innerHTML = "<h1>Employee Gross Pay Totals</h1><hr />";
        while(howMany--) {
            var employee = getInfo();
            employees.push(employee);
    
            targetDiv.innerHTML += "<b>Employee Name: </b>" + employee.name + "<br />";
            targetDiv.innerHTML += "<b>Total Hours Worked: </b>" + employee.payRate + "<br />";
            targetDiv.innerHTML += "<b>Hourly Pay Rate: </b>" + employee.hoursWorked + "<br />";
            targetDiv.innerHTML += "<b>Total due: </b>" + Math.round(employee.payRate * employee.hoursWorked) + "<br />";
    
            /* insert code statements to calculate hourly pay and overtime pay to equal gross pay */
    
        }
    };
    
    var getInfo = function() {
        return {
            name: prompt("Enter Name of Employee: ", ''),
            payRate: parseFloat(prompt("Enter the Hourly Rate of Pay: ", '')),
            hoursWorked: parseFloat(prompt("Enter the number of Hours last week: ", ''))
        };
    };
    
    window.onload = function() {
        calcPay(2); // 2 employees
    };
    
    </script>
    </body>
    </html>
    
    PHP:
     
    Last edited: Aug 2, 2009
    dimitar christoff, Aug 2, 2009 IP
  3. Chronia

    Chronia Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you dimitar!

    It was the name array that was causing the problem becasue it was a reserved word. I changed the name of the array and all instances of it to empName and the program did exactly what it should do and ran perfectly. Thanks so much for you help and advice!
     
    Chronia, Aug 2, 2009 IP