Andrew Pomorski Andrew Pomorski - 3 months ago 11
HTML Question

Passing select id and value from HTML to JavaScript

I'm writing a simple program in JavaScript - k20 dice calculator.
User can choose how many dice he wishes to throw, by HTML select :

<select id="kamount">
<option value="1" id="id1"> k20</option>
<option value="2" id="id2">2k20</option>
<option value="3" id="id3">3k20</option>
<option value="4" id="id4">4k20</option>
</select>


I want to pass the selection value to JavaScript function, which looks like this:

function dice_k20(dice){

if (dice == 1){
document.write(Math.floor((Math.random() * 20) + 1));
}
else if (dice == 2) {
for (i = 0; i <= 2; i++) {
document.write(Math.floor((Math.random() * 20) + 1));
}
}

else if (dice == 3) {
{
for (i = 0; i <= 3; i++) {
document.write(Math.floor((Math.random() * 20) + 1));
}
}

else if (dice == 4) {
{
for (i = 0; i <= 4; i++) {
document.write(Math.floor((Math.random() * 20) + 1));
}
}

}


I've been trying to pass the select value to the function, but it still doesn't work. The JS source code is in another file.

Thank you for help

Answer

Make sure your javascript file refer in your html document. Else Edit your javascript code like this(keep your dice_k20() function)

var dice_val = document.getElementById('kamount').value;
dice_k20(dice_val);