2

我有两个下拉选择框,我希望一个文本框根据两个框中的选定文本更新一个值。如果选择的第一个框是“美元”,第二个框是“奈拉”,我希望汇率为 100,并且这个值输入到带有汇率 id 的文本框中。

不幸的是,当我的函数执行时,我不断得到一个未定义的值。我的 if 语句显然有问题,但我无法弄清楚。我需要使用纯 javascript 来执行此操作,而不是 jquery。

这是我的代码:

<p>Select currency to send</p>  
<select id="fromCurrency">
<option value = "Dollars">Dollars</option>  
<option value = "Pounds">Pounds</option>
<option value = "Naira">Naira</option>
</select>

<p>Select currency to receive</p>
<select id="toCurrency">
<option value = "Naira">Naira</option>
<option value = "Dollars">Dollars</option>  
<option value = "Pounds">Pounds</option>

</select><br />
<label>Enter amount to send</label>
<input type="text" id="amount" name="amount"><br />
<button onclick ="getRate()">Get Rate</button><br />
<label>Rate:</label>
<input type="text" id="rate" name="rate"><br />
<label>Total:</label>
<input type="text" id="total" name="total"><br />



<script>

function getRate() {
var e = document.getElementById("fromCurrency");
var eSend = e.options[e.selectedIndex].value;
var i = document.getElementById('toCurrency');
var eReceive = i.options[i.selectedIndex].value;
var rate = document.getElementById('rate');

var dollars = {
'pounds':20,
'naira':15
};


if (eSend =='dollars' && eReceive =='naira') {
var rValue= (dollars['pounds']);
};  
rate.value = rValue;

};
</script>

请指教。谢谢

编辑:我尝试使用 switch 语句,因为我有大约 6 种不同的条件,这是我尝试过的,但没有奏效。

var rValue = 0;

switch (rValue) {
case (eSend =='Dollars' && eReceive =='Naira'):
rValue= (dollars['naira']);
break;
case (eSend =='Dollars' && eReceive =='Pounds'):
rValue= (dollars['pounds']);
break;
}

rate.value = rValue;
4

1 回答 1

5

JavaScript 是区分大小写的,你的 if 语句:

if (eSend =='dollars' && eReceive =='naira') {

正在寻找dollars,而不是Dollars,大写以匹配您的select值:

if (eSend =='Dollars' && eReceive =='Naira') {
于 2013-06-27T19:28:28.210 回答