SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Evangelist
    Join Date
    Jun 2004
    Posts
    417
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Fill form fields based on value of others

    Hi,

    does anyone have an example on how to fill a form field, based on the value of another form field?

    In my site, when a user selects a specific holiday, the price field needs to be updated with the correct price. If he selects another holiday, the price fields changes with it.

    I'm retreiving all data from a db.

    Many thanks in advance.

  2. #2
    I ♥ PHP
    Join Date
    Jul 2003
    Location
    Melbourne, Australia
    Posts
    579
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In Javascript you can access the various form fields by their ID. For instance:
    Code:
    var field = document.getElementById('fieldID');
    With this you can modify it's value with anything you like. If you are using PHP for instance to retrieve the data, maybe you can write the values in to a Javascript variable. Then you can perform calculations based on other selections and fill fields with that figure. Example:
    Code:
    var price1 = 125;
    var price2 = 200;
    var price3 = 250;
    
    var calculated = field1.value * price1;
    
    or
    
    var calculated = 0;
    
    if (field1.value == 1)
    {
       calculated = price1;
    }
    else if (field1.value == 2)
    {
       calculated = price2;
    }
    else if (field1.value == 3)
    {
       calculated = price3;
    }
    
    var field2 = document.getElementById('field2');
    
    field2.value = calculated;
    If you create a function that is called whenever one of your form fields is changed, then you can keep the "calculated" fields updated on-the-fly.

    Regards,
    Jordan

  3. #3
    SitePoint Evangelist
    Join Date
    Jun 2004
    Posts
    417
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Jordan,

    but how do I trigger the function then?

    For example,when field1 is filled in, and the focus goes to the next field, how do I update field3?

    Regards,
    Michel

  4. #4
    I ♥ PHP
    Join Date
    Jul 2003
    Location
    Melbourne, Australia
    Posts
    579
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    HTML Code:
    <input id="field1" onchange="calculate()" />
    then just wrap all of the code in the function named calculation.

    Regards,
    Jordan

  5. #5
    SitePoint Evangelist
    Join Date
    Jun 2004
    Posts
    417
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    And how can I use the retreived valu in a php script?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •