How to get selected option in JQuery

By FoxLearn 10/17/2024 9:10:58 AM   77
To get the selected option from a dropdown using jQuery, you can use the :selected selector or the .val() method.

For example:

<select id="product">
  <option value="1">Laptop</option>
  <option value="2">IPhone</option>
</select>
<button id="btn">Get Selected Option</button>

$('#id option:selected').text() gets the text of the currently selected option.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    $('#btn').click(function() {
       var selectedOption = $('#id option:selected').text();
    });
  });
</script>

$('#id').val() gets the value of the selected option.

$('#btn').click(function() {
      var selectedValue = $('#id').val();
});

You can choose either method depending on whether you need the value or the text of the selected option.