Reputation: 23
I have two dropdown select boxes and I want a textbox to update with a value based on the selected texts from the two boxes. If the first box selected is 'dollars' and the second is 'naira', I want the rate to be 100 and this value inputted in the textbox with the id of rate.
Unfortunately when my function executes I keep getting a value of undefined. Something is obviously wrong with my if statement but I can't figure it out.I need to do this with pure javascript, not jquery.
Here is my code:
<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>
Please advice. Thanks
EDIT: I tried to use a switch statement as I have about 6 different conditions, and this is what I tried but it didn't work.
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;
Upvotes: 2
Views: 180
Reputation: 104775
JavaScript is case-sensitive, your if statement:
if (eSend =='dollars' && eReceive =='naira') {
is looking for dollars
, not Dollars
, capitalize to match your select
values:
if (eSend =='Dollars' && eReceive =='Naira') {
Upvotes: 5