Javascript:获取所选选项的ID

时间:2016-01-10 13:58:40

标签: javascript

获取所选选项的值

$("#id_CITY").change(function() {
    var el = $(this);
    a = el.val()
)};

但我如何获得身份证?

1 个答案:

答案 0 :(得分:1)

通常,您不希望在id元素上option,因为没有什么意义。

但是,如果您有理由这样做,可以通过查找id并阅读其option:selected来获取所选选项的id

$("#id_CITY").change(function() {
    var el = $(this);
    var a = el.val(); // <== Note `var`
    var selectedId = el.find("option:selected").attr("id");
}); // <== Note you had a typo here; this is fixed

直播示例:

$("#id_CITY").change(function() {
    var el = $(this);
    var value = el.val();
    var selectedId = el.find("option:selected").attr("id");
    $("<p>").text(
      "value = '" + value + "', id = '" + selectedId + "'"
    ).appendTo(document.body);
});
<select id="id_CITY">
  <option id="first" value="1st">First</option>
  <option id="second" value="2nd">Second</option>
  <option id="third" value="3rd">Third</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>