首页 > 解决方案 > 如何使用 JavaScript 获取选定的文本 id

问题描述

我有一个这样的选择列表:

<select id="takimlar" placeholder="Randevu Alacağınız Takımınızı Seçiniz">
        <option value="" disabled selected>Randevu Alacak Takım</option>
        </select>

选项来自带有此代码的数据库

    var formData = new FormData();

    formData.append("email", kullaniciEmail);

    console.log("Form Data Bilgileri")
    console.log(formData);
    //kapat();
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "../backend/kullanici-takimlari-getir.php", true);
    xhr.send(formData);

    xhr.onload = function () {
        console.log(this.response);

        var res = this.response;
        res = JSON.parse(res);
        console.log(res)


        res.forEach(takim => {
        console.log(takim)   
        var option = document.createElement("option");
        option.text = takim.takimadi;
        option.value = takim.takimadi;
        var select = document.getElementById("takimlar");
        select.appendChild(option);
    });

因此,当我从网站上的选择列表中选择一个选项时,我想获取所选选项的 id(来自数据库)(不是文本或其值)。

我该怎么做?

标签: javascriptselect

解决方案


如果您不想使用选项的文本或值,则必须设置自己的属性。

res.forEach(takim => {
  console.log(takim)   
  var option = document.createElement("option");
  option.text = takim.takimadi;
  option.value = takim.takimadi;
  option.setAttribute('data-id', 'YOUR_ID_HERE');
  var select = document.getElementById("takimlar");
  select.appendChild(option);
});

然后,获取 的属性data-idselectedIndex

var select = document.getElementById("takimlar");
var id = select.options[select.selectedIndex].getAttribute('data-id');
// id contains the value of the data-id attribute

推荐阅读