Working out Percentage

Discussion in 'JavaScript' started by jwalker80, Jun 9, 2006.

  1. #1
    Hi,

    I am going to use javascript to calculate a value depending on what the user selects from a dropdown menu.

    I have 2 columns in a table and a dropdown menu. The value in the 2nd column is going to be calculated by taking a percentage of the number that is hardcoded in the 1st column.

    The user will select an option from the drop down e.g. 10% 20% 30% etc... and the value in the 2nd column will be calculated according to the percentage of the value in the 1st column.

    Anyone know a simple way to do this??
     
    jwalker80, Jun 9, 2006 IP
  2. mad4

    mad4 Peon

    Messages:
    6,986
    Likes Received:
    493
    Best Answers:
    0
    Trophy Points:
    0
    #2
    There is no really simple way to do it. :)

    You will need to store your hardcoded variables into either an array of as individual hidden variables and then multiply them by the percentage.

    Here is a scipt to calculate percentages.

    I suggest you create your html page with the items you want to calculate and then post back here so we can see exactly what you want.
     
    mad4, Jun 9, 2006 IP
  3. DonkeyTeeth

    DonkeyTeeth Peon

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    If you're using an HTML table, javascript can read the text or HTML in table cells, so you could loop through the whole table and dynamically calculate the new value for your second column. Something like this for each row:

    var x=document.getElementById('myTable').rows[0].cells[0].innerText;
    var xval=Number(x);
    var yval=xval*.25;
    var ystr=String(yval);
    document.getElementById('myTable').rows[0].cells[1].innerText=ystr;
    
    Code (markup):
    If the values in the first column are hardcoded, mad4's suggestion might be more efficient since you don't really need to dynamically read the value from each cell in that column.
     
    DonkeyTeeth, Jun 13, 2006 IP