Skip to content Skip to sidebar Skip to footer

Javascript Dropdown Updates The Price Based On The Users Selection Version 2?

I needed some help updating the price on a page based on a dropdown selection. This is what code with some help we came up with: var price = new Array('','$2.00','$45.00','$60.

Solution 1:

You're changing the price based on the value, and using that as the item from your price array... but your price array only has 4 values. In your second select, you're asking it to return price[4] or price[5], which would cause an error.

Change this:

var price = new Array('','$2.00','$45.00','$60.00');

To this:

var price = new Array('','$2.00','$45.00','$60.00','$cloth price','$upvc price');

Fiddle here.

EDIT: Updated method (with minimal change to your existing layout/logic)

$(function() {
    $('select[name=material]').change(function() {
        var price = $(this).val().split("_");
        $("#id").html(price[0]);
        $("#price").html("$" + price[1]);
    });
});

HTML (adding the price to each option value, split by "_" in JS)

<select name="material">
    <option value="0_0">-- Please Select --</option>
    <option value="1_2">Wood</option>
    <option value="2_2">Plastic</option>
    <option value="3_45">Metal</option>
</select>

<select name="material">
    <option value="0_0">-- Please Select --</option>
    <option value="3_60">Metal</option>
    <option value="4_50">Cloth</option>
    <option value="5_80">UPVC</option>
</select>

<div>ID: <span id="id">TBD</span><br />Price: <span id="price">TBD</span></div>

Solution 2:

Just select price using the selectedIndex of your <select>:

var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
    $('select[name=material]').change(function(){
        document.getElementById('pprice').innerHTML = price[this.selectedIndex];
    });

    // Trigger on dom ready
    $('select[name=material]').change();
});

Or, use an object instead of an array for price:

var price = {
    "4": "$2.00",
    "5": "$45.00",
    "6": "$60.00"
};
$(function(){
    $('select[name=material]').change(function(){
        document.getElementById('pprice').innerHTML = price[$(this).val()];
    });

    // Trigger on dom ready
    $('select[name=material]').change();
});

Solution 3:

Update: Here is a jsfiddle with updated code to get your single price array to work:

Your price arrayhas a length of 4 and starts at index 0.

Your first option must have a value of '0' or it will return undefined from the price array:

<select name="material">
    <option value="0">-- Please Select --</option>
    <option value="1">Wood</option>
    <option value="2">Plastic</option>
    <option value="3">Metal</option>
</select>

When you set your option values from 3 to 5, you are trying to access non-existent indexes outside the bounds of your price array.


Post a Comment for "Javascript Dropdown Updates The Price Based On The Users Selection Version 2?"