How can I make variable form values based on some javascript arrays?

Discussion in 'JavaScript' started by mikemdg, Oct 18, 2010.

  1. #1
    Here is what I'm trying to do... I have a form with an input field named "investment" followed by 5 fields that you can type percentages into for 1-5 year interest rates.
    Example:
    Investment ________
    rate 1 _____%
    rate 2 _____% etc...

    I want the 5 rate fields to change based on the amount entered into the investment field... Example:

    <SCRIPT LANGUAGE="text/javascript">
    <!--
    if (investment.value <= 1000)
    var range = 1;
    else if (investment.value >= 1001 && <= 5000)
    var range = 2;
    else if (investment.value >= 5001 && <= 10000)
    var range = 3;
    else if (investment.value >= 20000)
    var range = 4;
    }
    // -->
    </SCRIPT>


    So there are 4 different sets of numbers stored in arrays based on how much you are investing and give a variable called $range which can be 1,2,3 or 4)

    so all the range values would be stored in arrays:

    var minDep1=new Array();
    minDep1[0]="1.25";
    minDep1[1]="1.35"; etc...

    ...and I want to drop those values into the form fields when the user types in how much they are investing:

    <input name="oneyear" type="text" id="oneyear" value="minDep1[0]" size="5" maxlength="5">
    <input name="twoyear" type="text" id="twoyear" value="minDep1[1]" size="5" maxlength="5">
    etc...

    The only problem is that I want the form to be able to select which range (onchange) and then replace the field value with the proper array. So if it was range 1, the value would be: value="minDep1[0]"... if range 2 was selected, it would be the next array: value="minDep2[0]"...

    so can I somehow make the value field dynamically select the appropriate array so that it selects the proper range, ex:
    <input name="oneyear" value="minDep($range variable 1-4 goes here)[0]">
     
    mikemdg, Oct 18, 2010 IP
  2. kai555

    kai555 Peon

    Messages:
    18
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi

    Create a select and add values 1-4 in the options with a onchange event
    <select onchange="change" id='range'>
    <option value=1>range 1</option>
    .
    .
    <option value=4>range 4</option>
    </select>

    instead of having 4 arrays you can have one 2Dimensional array. Then in your function simply set the values according to what was selected:

    selected=document.getElementById('range').value;
    document.getElementById('rate1').value=myarray[selected][1];
    .
    .
    document.getElementById('rate2').value=myarray[selected][2];
     
    kai555, Oct 21, 2010 IP