简体   繁体   中英

Get value of selected option in javascript

 function Play() { var option = ["Rock", "Paper", "Scissors"]; var randomOption = option[Math.floor(Math.random()*option.length)]; console.log(randomOption) var UserOption = document.getElementById('UserSelect'); console.log(UserOption); } Play();
 <div class="form-group"> <select class="form-control" id="UserSelect"> <option value="1">Rock</option> <option value="2">Paper</option> <option value="3">Scissors</option> </select> </div>

I'm trying to save the selected option in UserOption. I can't seem to figure out what I am doing wrong.

You just need to get the value of the select, like this:

var UserOption  = document.getElementById('UserSelect').value;

Then you can get the name from the options array like this:

console.log(options[UserOption-1])

Working Snippet

 function Play() { var option = ["Rock", "Paper", "Scissors"]; var randomOption = option[Math.floor(Math.random()*option.length)]; var UserOption = document.getElementById('UserSelect').value; console.log("Player:" +option[UserOption-1] + " vs Computer:" + randomOption ); }
 <body> <div class="form-group"> <select class="form-control" id="UserSelect"> <option value="1">Rock</option> <option value="2">Paper</option> <option value="3">Scissors</option> </select> </div> <button class="play" onclick="Play();">Play</button> </body>

You can call you play() function using onchange function on your select and passing this as the argument

In your Play() function just get the option selected Index and get it textContent to see what was selected

Also, please ensure that your script tags are added after the </body> end and not in head of the page

 function Play(e) { var option = ["Rock", "Paper", "Scissors"]; var randomOption = option[Math.floor(Math.random() * option.length)]; console.log(randomOption) var UserOption = e.options[e.selectedIndex].textContent; console.log(UserOption); }
 <body> <div class="form-group"> <select class="form-control" id="UserSelect" onchange="Play(this)"> <option selected disabled>Choose</option> <option value="1">Rock</option> <option value="2">Paper</option> <option value="3">Scissors</option> </select> </div> </body>

The option value is stored inside the value attribute.

  var UserOption = document.getElementById('UserSelect').value;
  console.log(UserOption);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM