jQuery从下拉列表中获取选定的选项

JavaScript

Mandy猴子

2020-03-09

通常,我使用它$("#id").val()来返回所选选项的值,但这一次它不起作用。所选标签的IDaioConceptName

HTML代码

<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>

第382篇《jQuery从下拉列表中获取选定的选项》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
Near理查德路易 2020.03.10

You can select using exact selected option : Below will give innerText

$("select#aioConceptName > option:selected").text()

While below will give you value.

$("select#aioConceptName > option:selected").val()
老丝村村 2020.03.10

You can use $("#drpList").val();

小小阿飞 2020.03.10

Use the jQuery.val() function for select elements, too:

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

$(function() {
  $("#aioConceptName").on("change", function() {
    $("#debug").text($("#aioConceptName").val());
  }).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<select id="aioConceptName">
  <option>choose io</option>
  <option>roma</option>
  <option>totti</option>
</select>
<div id="debug"></div>

米亚Near 2020.03.10

尝试此物有所值...

$("select#id_of_select_element option").filter(":selected").val();

或这个文本...

$("select#id_of_select_element option").filter(":selected").text();

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android