Reputation:
I'm learning Javascript events, but I have a problem about the value I type in an input.
When I type a number, the calcul needs to be change (keyup). Same thing about the option that I choose (change).
But the value that I return with my paragraph (id=res) is undifined. I don't understand what it means and how to debug it.
// Here is the Javascript for my events (keyup and change).
document.getElementById("selectDevice").addEventListener('change', change);
document.getElementById("montant").addEventListener('keyup', change);
function change(e) {
var montant = Number.parseInt(document.getElementById("montant").value, 10);
var selectDevice = document.getElementById("selectDevice").value;
switch (e.target.id) {
case 'nothing':
var resultat = montant;
console.log(resultat);
break;
case 'usd':
var resultat = montant * 1.14;
console.log(resultat);
break;
case 'eur':
var resultat = montant * 0.82;
console.log(resultat);
break;
}
document.getElementById("res").innerHTML = resultat
}
<!-- Here is the HTML -->
Amount: <input id="montant" type="text" />
Device:
<select id="selectDevice">
<option id="nothing" value="nothing">Please choose a device</option>
<option id="usd" value="eur">EUR</option>
<option id="eur" value="usd">USD</option>
</select>
Convert amount: <span id="res"></span>
I'm speaking french, I didn't translate all my code, but if you have some questions, I'm here =)
If you have some solutions from the Javascript Documentation, thank you to give me the page, because I need to learn to search in the doc in order to find my solutions by myself.
Have a nice day =)
Upvotes: 1
Views: 1369
Reputation: 21684
Your switch
statement was looking at the ID of the element triggering it, which has 2 problems:
selectDevice
.This only needs a tiny fix:
// Here is the Javascript for my events (keyup and change).
document.getElementById("selectDevice").addEventListener('change', change);
document.getElementById("montant").addEventListener('keyup', change);
function change(e) {
var montant = Number.parseInt(document.getElementById("montant").value, 10);
var selectDevice = document.getElementById("selectDevice").value;
switch (selectDevice) { // changed this and that was it.
case 'nothing':
var resultat = montant;
console.log(resultat);
break;
case 'usd':
var resultat = montant * 1.14;
console.log(resultat);
break;
case 'eur':
var resultat = montant * 0.82;
console.log(resultat);
break;
}
document.getElementById("res").innerHTML = resultat
}
<!-- Here is the HTML -->
Amount: <input id="montant" type="text" />
Device:
<select id="selectDevice">
<option id="nothing" value="nothing">Please choose a device</option>
<option id="usd" value="eur">EUR</option>
<option id="eur" value="usd">USD</option>
</select>
Convert amount: <span id="res"></span>
Upvotes: 3