I am creating a calculator for a game and I want to use a drop down menu to select a value in a switch statement; although it doesn't seem to be working, it always returns 0. Can anyone see where I went wrong? Also I am fairly new to java and html so sorry if there is a dumb mistake.
Here is my html:
<form onsubmit="return calcDarkTroops(0);" style="display: inline;">
<!-- Title of Form /--> <font>Level</font>
<!-- Gets Input /-->
<select id="minionlevel_input">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
<!-- Calls 'calcDarkTroops' /-->
<input type="button" value="Calculate" onclick="calcDarkTroops();">
<!-- Outputs result /--> <span id="minioncost_result"> = 0 Dark Elixer</span>
Here is my Java:
calcDarkTroops = function () {
var minionlevel = Number(document.getElementById("minionlevel_input").value);
String maxString;
switch (minionlevel) {
case 1:
maxString = "200,000";
break;
case 2:
maxString = "190,000";
break;
case 3:
maxString = "170,000";
break;
case 4:
maxString = "140,000";
break;
case 5:
maxString = "100,000";
break;
case 6:
maxString = "0";
document.getElementById("minioncost_result").innerHTML = "= " + Math.round(maxString * 100) / 100 + " Dark Elixer";
}
Try providing the value attribute to your select option and also consider providing default option,
<select id="minionlevel_input">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
Try this:
<form style="display: inline;">
<!-- Title of Form /--> <font>Level</font>
<!-- Gets Input /-->
<select id="minionlevel_input">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
<!-- Calls 'calcDarkTroops' /-->
<input type="button" value="Calculate" onclick="return calcDarkTroops(document.getElementById('minionlevel_input').value)">
<!-- Outputs result /--> <span id="minioncost_result"> = 0 Dark Elixer</span>
<script>
function calcDarkTroops(minionlevel) {
var maxString;
switch (minionlevel) {
case '1':
maxString = "200,000";
break;
case '2':
maxString = "190,000";
break;
case '3':
maxString = "170,000";
break;
case '4':
maxString = "140,000";
break;
case '5':
maxString = "100,000";
break;
case '6':
maxString = "0";
break;
}
document.getElementById("minioncost_result").innerHTML = "= " + Math.round(parseInt(maxString) * 100) / 100 + " Dark Elixer";
}
See this fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.