CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   JavaScript Functions in separate .js files not working properly (http://www.codingforums.com/showthread.php?t=286939)

NinKenDo79 02-02-2013 11:59 PM

JavaScript Functions in separate .js files not working properly
 
I am very new to JavaScript and am working on an assignment for school that should be very simple but I can't get it working and am not getting much help.

I have a simple HTML file and two .js files each with a function that are all supposed to work together. Currently it will only output the pay calculation and not the overtime or that calcTaxes function at all.

Here is my HTML:

Code:


<html>
        <head>
                <meta http-equiv="Content-Type"
                content="text/html; charset=iso-8859-1">
       
        <title>Payroll Calculations</title>

        <script type="text/JavaScript" src="calcGrossPay.js" src="calcTaxes.js"> </script>
 
          </head>
    <body>
           
        <h1>Pay Calulator</h1>
        <script>
                var hoursWorked=prompt("Enter your total hours: ", "Hours");
                var payRate=prompt("Enter your pay rate: ", "Rate");
                document.writeln("Your total pay is: $" +
                calcGrossPay(hoursWorked, payRate));
                document.writeln("Your total taxes are: $" + calcTaxes(pay));
        </script>
        </body>
</html>

my 1st .js

Code:


function calcGrossPay(payRate, hoursWorked){

        var pay = "";
        var rate = payRate;
        var hours = hoursWorked;
        var overTime = "";
        var otPay = "";
       
        if(hours>40){
                overTime = hours % 40;
                otPay = (overTime * rate) * 1.5;
                pay = (40 * rate) + otPay;

        }
        else {
                pay = hours * rate;
       
        }
                pay = pay.toFixed(2);
       
        return pay;
}

and my 2nd .js

Code:


function calcTaxes(pay){
       
        var fed = .31;
        var state = .08;
        var local = .02;
        var pay = pay;
        var tempLocal = "";
        var tempState = "";
        var tempFed = "";
        var taxTotal = "";
       
        tempLocal = pay*local;
        pay = pay-tempLocal;
        tempState = pay * state;
        pay = pay-tempState;       
        tempFed = pay*fed;
       
        taxTotal = tempLocal+tempState+tempFed;
       
        taxTotal = taxTotal.toFixed(2);
       
        return taxTotal;       
}

Thank you so much for any help you can offer!

Ken D.

jmrker 02-03-2013 12:17 AM

Both 1st.js and 2nd.js scripts could be in one file named calcTaxes.js
There are NO HTML tags (like <script ...>) in that text file.
Should also be in the same directory unless you change the path.

OR Call as 2 separate <script type="text/JavaScript ... tags with the lower case "j" and "s"
Code:

        <script type="text/javascript" src="calcTaxes.js"> </script>
        <script type="text/javascript" src="calcGrossPay.js"> </script>

:)

billboy 02-03-2013 07:30 AM

his was very helpful as I am just learning I weas curious as to how to create and reference js files so I didnt have to have the scripts in my HTML pages
How can you get the value from a JS function that is in a seperate file to an inputbox on another page?

Code:

if (!Array.prototype.reduce) {
  Array.prototype.reduce = function reduce(accumulator){
    if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
    var i = 0, l = this.length >> 0, curr;

    if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
      throw new TypeError("First argument is not callable");

    if(arguments.length < 2) {
      if (l === 0) throw new TypeError("Array length is 0 and no second argument");
      curr = this[0];
      i = 1; // start accumulating at the second element
    }
    else
      curr = arguments[1];

    while (i < l) {
      if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
      ++i;
    }

    return curr;
  };
}



function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}



function centNotation(value)
 {

 dollars = Math.floor(value); // chop floating point portion
 cents = Math.floor((value % 1) * 100); // and chop everything else
 if (cents < 10) cents = "" + cents + "0";
 return(dollars + "." + cents);
 }


function validInt(value)
{
 

  for (var i=0; i < value.length; i++) {
    var c = value.charAt(i);
    if ((c < '0' || c > '9') && c != '.') {
      alert("There's a problem: all values herein must " +
        "be numbers only, and " + value + " has an unacceptable character " +
        "'" + c + "'");
      return(false);
    }
  }
  return(true);
}

function myPaymentCalc()
{
 
 
  var interestRate = document.debtcalc.interest.value,
      monthlyPayment = document.debtcalc.monthlypayment.value,
      principal = document.debtcalc.principal.value,
      accumulatingInterest = 1;
 
  if (! validInt(interestRate) || ! validInt(monthlyPayment) ||
      ! validInt(principal))
    return(false);
   
  if (interestRate == 0 || monthlyPayment == 0 || principal == 0) {
    alert("You need to specify your monthly payment, credit card " +
        "interest rate and current debt amount before I can calculate " +
        "how long it'll take for you to pay off your debt.");
    return(false);
  }
 
  interestRate = (interestRate > 1)? interestRate / 100.0 : interestRate;

  monthlyInterestRate = interestRate / 12;

  if (principal * monthlyInterestRate > monthlyPayment) {
    monthlyrate = "$" + centNotation(principal * monthlyInterestRate);
    permonthPayment = "$" + centNotation(monthlyPayment);
    alert("You've got a fundamental problem: your monthly payment of " +
        permonthPayment + " is less than the interest added each month " +
        "(which is " + monthlyrate + ") and you will never " +
        "pay off this debt. It might be a good time to call your creditors.");
    return(false);
  }
 
  interimVal1 = monthlyPayment - (monthlyInterestRate * principal)
 
  numberOfPayments = (Math.log(monthlyPayment) - Math.log(interimVal1)) /
        Math.log(1+monthlyInterestRate);
 
  numberOfPayments = Math.ceil(numberOfPayments);
     
  interimVal2 = Math.pow((monthlyInterestRate+1), (numberOfPayments-1));
 
  remaining = (principal * interimVal2) -
    (monthlyPayment/monthlyInterestRate) * (interimVal2 - 1);
   
  totalPayment = monthlyPayment *(numberOfPayments-1) + remaining;
 
 
       
  payments = numberOfPayments;
 <!-- totalpayment = "$" + centNotation(totalPayment);-->
 <!-- interestPaid = "$" + centNotation(totalPayment-principal);-->


  totalpayment = formatDollar(totalPayment);
  interestPaid = formatDollar(totalPayment-principal);
 
  alert("Given these figures, you'll end up having " + payments +
        " payments and pay a total of " + totalpayment + ", of which " +
        interestPaid + " is interest.");

document.debtcalc.numberofpayments.value = payments;  these represent inputboxes that got populated
document.debtcalc.totalpayments.value = totalpayment;    They dont get populated if I place this script in a seperate file
document.debtcalc.intpmt.value = interestPaid;                Everything else works so I am referencing it correctly just not populating the HTML boxes properly

}
</script>

If this script is in my HTML page it works fine, but if I place it in a seperate file and reference it from my HTML page then the last 3 lines do NOT work
I am sure I need to reference them differently but not sure how

Philip M 02-03-2013 10:01 AM

Quote:

Originally Posted by billboy (Post 1310615)
document.debtcalc.numberofpayments.value = payments; these represent inputboxes that got populated
document.debtcalc.totalpayments.value = totalpayment; They dont get populated if I place this script in a seperate file
document.debtcalc.intpmt.value = interestPaid; [I]Everything else works so I am referencing it correctly just not populating the HTML boxes properly
}
</script>[/CODE]

If this script is in my HTML page it works fine, but if I place it in a seperate file and reference it from my HTML page then the last 3 lines do NOT work
I am sure I need to reference them differently but not sure how

The HTML elements must exist before they are referenced by the Javascript.
Place your calls to the .js files right in front of the </body> tag. That is the correct place to put scripts.

Code:

<script type="text/javascript" src="calcTaxes.js"> </script>
<script type="text/javascript" src="calcGrossPay.js"> </script>
</body>


billboy 02-03-2013 10:23 AM

?? They do exist??

Again the js works, but not getting the values in my html elements

i will move them and see

that seemed to do the trick , although my formatDollar doesnt seem to be working

Philip M 02-03-2013 11:12 AM

Quote:

Originally Posted by billboy (Post 1310633)
that seemed to do the trick , although my formatDollar doesnt seem to be working

Have you tried using your error console? What error messages do you receive? reduce() is not supported by all browsers.

Or try this:-

Code:

<script type="text/javascript">

// works with negative numbers also
function formatNumber(x) {
return x.toFixed(2).split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
}

var num = formatNumber(1234567.8897);
num = "$" + num;
alert (num);

</script>


billboy 02-03-2013 09:50 PM

I am now getting an error "payments" is undefined

This is the code in a seperate js file


Code:

if (!Array.prototype.reduce) {
  Array.prototype.reduce = function reduce(accumulator){
    if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
    var i = 0, l = this.length >> 0, curr;

    if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
      throw new TypeError("First argument is not callable");

    if(arguments.length < 2) {
      if (l === 0) throw new TypeError("Array length is 0 and no second argument");
      curr = this[0];
      i = 1; // start accumulating at the second element
    }
    else
      curr = arguments[1];

    while (i < l) {
      if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
      ++i;
    }

    return curr;
  };
}



function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}



function centNotation(value)
 {

 dollars = Math.floor(value); // chop floating point portion
 cents = Math.floor((value % 1) * 100); // and chop everything else
 if (cents < 10) cents = "" + cents + "0";
 return(dollars + "." + cents);
 }


function validInt(value)
{
 

  for (var i=0; i < value.length; i++) {
    var c = value.charAt(i);
    if ((c < '0' || c > '9') && c != '.') {
      alert("There's a problem: all values herein must " +
        "be numbers only, and " + value + " has an unacceptable character " +
        "'" + c + "'");
      return(false);
    }
  }
  return(true);
}

function myPaymentCalc()
{
 
 
  var interestRate = document.debtcalc.interest.value,
      monthlyPayment = document.debtcalc.monthlypayment.value,
      principal = document.debtcalc.principal.value,
      accumulatingInterest = 1;
 
  if (! validInt(interestRate) || ! validInt(monthlyPayment) ||
      ! validInt(principal))
    return(false);
   
  if (interestRate == 0 || monthlyPayment == 0 || principal == 0) {
    alert("You need to specify your monthly payment, credit card " +
        "interest rate and current debt amount before I can calculate " +
        "how long it'll take for you to pay off your debt.");
    return(false);
  }
 
  interestRate = (interestRate > 1)? interestRate / 100.0 : interestRate;

  monthlyInterestRate = interestRate / 12;

  if (principal * monthlyInterestRate > monthlyPayment) {
    monthlyrate = "$" + centNotation(principal * monthlyInterestRate);
    permonthPayment = "$" + centNotation(monthlyPayment);
    alert("You've got a fundamental problem: your monthly payment of " +
        permonthPayment + " is less than the interest added each month " +
        "(which is " + monthlyrate + ") and you will never " +
        "pay off this debt. It might be a good time to call your creditors.");
    return(false);
  }
 
  interimVal1 = monthlyPayment - (monthlyInterestRate * principal)
 
  numberOfPayments = (Math.log(monthlyPayment) - Math.log(interimVal1)) /
        Math.log(1+monthlyInterestRate);
 
  numberOfPayments = Math.ceil(numberOfPayments);
     
  interimVal2 = Math.pow((monthlyInterestRate+1), (numberOfPayments-1));
 
  remaining = (principal * interimVal2) -
    (monthlyPayment/monthlyInterestRate) * (interimVal2 - 1);
   
  totalPayment = monthlyPayment *(numberOfPayments-1) + remaining;
       
  payments = numberOfPayments;
 totalpayment = "$" + centNotation(totalPayment);
 interestPaid = "$" + centNotation(totalPayment-principal);


 <!-- totalpayment = formatDollar(totalPayment);-->
 <!-- interestPaid = formatDollar(totalPayment-principal);-->


 
 
  alert("Given these figures, you'll end up having " + payments +
        " payments and pay a total of " + totalpayment + ", of which " +
        interestPaid + " is interest.");

document.debtcalc.numberofpayments.value = payments;
document.debtcalc.totalpayments.value = totalpayment;
document.debtcalc.intpmt.value = interestPaid;


}



All times are GMT +1. The time now is 07:05 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.