[SOLVED] Get text from pull down list – not working (HTML/JQuery)

Issue

This Content is from Stack Overflow. Question asked by Brian S

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>


Solution

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>

This Question was asked in StackOverflow by Brian S and Answered by Michael M. It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version