How can I display a Dynamic Price from a dropdown menu?

Discussion in 'JavaScript' started by mcfc4eva, Dec 16, 2010.

  1. #1
    Hi,

    I've been trying to figure out how to display a "dynamic price" that changes when the user selects a product from a drop down menu.

    For example;
    I would like the price (in the div) to update automatically when the user selects one of the products. Is this possible?

    P.S. I don't actually sell meat, cheese, bread & milk. They're just examples to simplify the problem :p
     
    mcfc4eva, Dec 16, 2010 IP
  2. animebuzz.tv

    animebuzz.tv Peon

    Messages:
    317
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    are using javascript framework or pure javascrit?
     
    animebuzz.tv, Dec 16, 2010 IP
  3. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yeah, there are several ways to do that. This method works with your code:
    
    <html>
    <head><title>My Title!</title>
    <script type="text/javascript">
       function updatePrice() {
          var dropdown = document.getElementsByName("product")[0];
          var price = dropdown.options[dropdown.selectedIndex].text;
          var idx = price.indexOf("$");
          price = price.slice(idx, price.length - 1);
          document.getElementById("price").innerHTML="<p>PRICE: " + price + "</p>";
       }
    </script>
    </head>
    <body onload="updatePrice()">
    <select name="product" onchange="updatePrice()">
    <option value="meat">Meat ($10.00)</option>
    <option value="cheese">Cheese ($5.00)</option>
    <option value="bread">Bread ($1.00)</option>
    <option value="milk">Milk ($2.00)</option>
    </select>
    <div id="price"><p>PRICE: $XX.XX</p></div>
    </body>
    </html> 
    
    Code (markup):
    But I like this method better:
    
    <html>
    <head><title>My Title!</title>
    <script type="text/javascript">
       function updatePrice() {
          var price = document.getElementById("product").value;
          document.getElementById("price").innerHTML="<p>PRICE: " + price + "</p>";
       }
    </script>
    </head>
    <body onload="updatePrice()">
    <select id="product" onchange="updatePrice()">
    <option id="meat" value="$10.00">Meat ($10.00)</option>
    <option id="cheese" value="$5.00">Cheese ($5.00)</option>
    <option id="bread" value="$1.00">Bread ($1.00)</option>
    <option id="milk" value="$2.00">Milk ($2.00)</option>
    </select>
    <div id="price"><p>PRICE: $XX.XX</p></div>
    </body>
    </html>
    
    Code (markup):
     
    Last edited: Dec 16, 2010
    Cash Nebula, Dec 16, 2010 IP