SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Kinda Newbie Question - Select Option Value

    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.


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

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,892
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    You can do it like this:

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

    HTH

  3. #3
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for the quick response, sir.
    Is it possible for me to print the value from there?

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

    Is this the correct way to do it?

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,892
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    Quote Originally Posted by IamJay View Post
    Is it possible for me to print the value from there?
    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


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •