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 = newArray('','$2.00','$45.00','$60.00');

To this:

var price = newArray('','$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)

<selectname="material"><optionvalue="0_0">-- Please Select --</option><optionvalue="1_2">Wood</option><optionvalue="2_2">Plastic</option><optionvalue="3_45">Metal</option></select><selectname="material"><optionvalue="0_0">-- Please Select --</option><optionvalue="3_60">Metal</option><optionvalue="4_50">Cloth</option><optionvalue="5_80">UPVC</option></select><div>ID: <spanid="id">TBD</span><br />Price: <spanid="price">TBD</span></div>

Solution 2:

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

var price = newArray('','$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:

<selectname="material"><optionvalue="0">-- Please Select --</option><optionvalue="1">Wood</option><optionvalue="2">Plastic</option><optionvalue="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?"