Kinda Newbie Question - Select Option Value

[FONT=Tahoma]Good day,

I guess this’ll be my first post. Lol. Anyways,

I’m a beginner in JS programming, I would just like to know how can I get the value of an Option from a Select Box.
Like this one, I’m creating a game which allows the user to select different game difficulties.
If a player chooses Hard as the game difficulty, the AI will then increase its possibility of winning.
How can I get the value of that option to increase the AI’s difficulty.


<select name="difficulty" id="difficulty">
	<option value="easy" selected="selected">Easy</option>
	<option value="normal">Normal</option>
	<option value="hard">Hard</option>
</select>

[/FONT]

Hi,

You can do it like this:

var sel = document.getElementById("difficulty");
var diff = sel.options[sel.selectedIndex].value;

HTH

Thank you for the quick response, sir.
Is it possible for me to print the value from there?


var sel = document.getElementById("difficulty");
var diff = sel.options[sel.selectedIndex].value;
alert(diff);

Is this the correct way to do it?

Hi,

It all depends on what you mean by “print”.

JavaScript’s alert() method displays a simple modal message box.
You could also log the output to the console using console.log()
Or you could insert the output somewhere in your page, using (for example) element.innerHTML