1

I am trying to get the selected item from a pull down list. I am using the following code to attempt to get the item selected. However, no matter what is selected in the pulldown menu (it has a checkmark indicating it is selected) I only get the first room listed (in this case "testing) and not the selected one. Why would this happen?

Here is what I am using to select -

var value = $(".room").val()

Here is the html code of the list:

<select>
<option class="room" value="testing">testing</option>
<option class="room" value="hello">hello</option>
<option class="room" value="lobby">lobby</option>
<option class="room" value="this is a test room">this is a test room</option>
<option class="room" value="gabe and samsons cave">gabe and samsons cave</option>
<option class="room" value="gabe">gabe</option>
<option class="room" value="rfe2209">rfe2209</option>
</select>
Brian S
  • 13
  • 2
  • may be you are trying to get the value of selected option, if so you need to grab the `select` element not the option. you can try this one too `$("select").change(function(){ alert("Value: " + $(this).val()); });` – Moshiur Sep 19 '22 at 06:51
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 19 '22 at 06:53
  • Does this answer your question? [Get selected value of a dropdown's item using jQuery](https://stackoverflow.com/questions/2780566/get-selected-value-of-a-dropdowns-item-using-jquery) –  Sep 19 '22 at 11:53

1 Answers1

0

You're selecting the value wrong. Only the <select>'s value will have the value of the selected <option>. Here's an example of working code:

$('#room').change(function() {
  const value = $('#room').val()
  console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="room">
  <option value="testing">testing</option>
  <option value="hello">hello</option>
  <option value="lobby">lobby</option>
  <option value="this is a test room">this is a test room</option>
  <option value="gabe and samsons cave">gabe and samsons cave</option>
  <option value="gabe">gabe</option>
  <option value="rfe2209">rfe2209</option>
</select>
Michael M.
  • 10,486
  • 9
  • 18
  • 34