案例选择Javascript下拉列表

时间:2012-10-03 20:16:29

标签: javascript switch-statement getelementbyid

所以这是我第一次尝试使用Javascript。我基本上试图根据下拉框中选择的值生成唯一的DIV。我有它来显示DIV,但值不会根据所选内容而改变。这是我到目前为止所得到的:

jsfiddle

正如您所看到的,当选择$ 200,000范围时,我想生成我已经计算过的固定值。我很想知道是否有一个开关或案例选择语句,我可以以某种方式产生,以根据下拉列表中选择的实际选项更改DIV。任何指向正确方向的人都会非常感激。

2 个答案:

答案 0 :(得分:1)

如果您不想使用jQuery,可以尝试切换select并设置value1,value2,value3的innerHTML

    switch(document.getElementById('mySelect').value)
{
    case '0': 
        document.getElementById('value1').innerHTML ='Principal and Interest only: $898';
        document.getElementById('value2').innerHTML = 'Estimated total monthly payment: $1,098';
        document.getElementById('value3').innerHTML ='VA loan payment:';    
        break;   
    case '1': 
        document.getElementById('value1').innerHTML ='Principal and Interest only: $998';
        document.getElementById('value2').innerHTML = 'Estimated total monthly payment: $2,098';
        document.getElementById('value3').innerHTML ='VA loan payment: $25';    
        break;          
    etc...
}

答案 1 :(得分:0)

以下是使用jQuery执行此操作的方法:

<select id="mySelect" onchange="showhide(this)">
    <option value="">Desired Home Price:</option>
    <!-- the option values are suffixes for the elements to show -->
    <option value="0">$200,000</option>
    <option value="1">$175,000</option>
    <option value="2">$150,000</option>
    <option value="3">$125,000</option>
    <option value="4">$100,000</option>
    <option value="5">$75,000</option>
    <option value="6">$50,000</option>
</select>

<div class="answer0 answers" style="width:200px;height:200px;display:none">
<div id="value1">Principal and Interest only: $898</div> 
<div id="value2">Estimated total monthly payment: $1,098</div>
<div id="value3">VA loan payment:</div>
<div id="value4">Another field:</div>
</div>

<div class="answer1 answers" style="width:200px;height:200px;display:none">
<div id="value1a">Principal and Interest only: $898.00</div> 
<div id="value2a">Estimated total monthly payment: $1,098.00</div>
<div id="value3a">VA loan payment:</div>
<div id="value4a">Another field:</div>
</div>



<script type="text/javascript">

function showhide(id) {
    var mySel = $(id).val()
    $('.answers').hide()  
    $('.answer'+mySel).show()  
}

</script>