📌  相关文章
📜  jquery select option value selected - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:44.120000             🧑  作者: Mango

jQuery Select Option Value Selected - JavaScript

If you're working with jQuery and need to select an option from a dropdown menu based on its value, you can use the val() method in combination with the :selected selector.

Syntax
$(selector).val(value);
Example
<select id="dropdown">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>
// select Option 2
$('#dropdown').val('option2');
Explanation

In the example above, we have a dropdown with three options. To select the second option with a value of option2, we use jQuery to select the dropdown element with the ID of dropdown and call the val() method on it with the argument of option2.

We could also use the :selected selector to get the value of the currently selected option:

var selectedValue = $('#dropdown option:selected').val();