Javascript下拉列表根据用户选择版本2更新价格? [英] Javascript dropdown updates the price based on the users selection version 2?

查看:121
本文介绍了Javascript下拉列表根据用户选择版本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.00');
    $(function(){
        $('select[name=material]').change(function(){
          document.getElementById('pprice').innerHTML = price[$(this).val()];
        }); 

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

如果我的下拉列表结构如下:

Which works if my dropdown is structured like this:

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

但是,如果由于任何原因,下拉菜单如下所示:

But if for any reason the the dropdown was to be like this:

    <select name="material">
        <option value="">-- Please Select --</option>
        <option value="3">Metal</option>
        <option value="4">Cloth</option>
        <option value="5">UPVC</option>
    </select>

它不会工作(因为值选项不是1,2,3)。该值是该材料的ID。希望这是有道理的,有人可以帮助我让这个工作。

it would not work (because the value option is not 1,2,3). The value is the id for the material. Hope this makes sense and that someone can help me to get this working.

感谢
Dino

Thanks Dino

推荐答案

只需使用< select> 中的 selectedIndex

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();
});

这篇关于Javascript下拉列表根据用户选择版本2更新价格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆