javascript - 如何使用 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(来自数据库)(不是文本或其值)。
我该怎么做?
解决方案
如果您不想使用选项的文本或值,则必须设置自己的属性。
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-id
值selectedIndex
。
var select = document.getElementById("takimlar");
var id = select.options[select.selectedIndex].getAttribute('data-id');
// id contains the value of the data-id attribute
推荐阅读
- excel - 使用表名检查特定表是否存在时的 VBA Excel 错误处理
- r - 使用与列表中的值匹配的多列过滤或子集数据框
- ios - swift:下载百分比
- java - 一个类可以扩展一个抽象类并同时实现一个接口吗?(爪哇)
- angular - Angular 5 中的路由器模块不起作用,如何使用它?
- c# - 包含的 aspx 页面中的 ASP.NET BC30198 错误
- report - 将参数从一个子数据集传递到 BIRT 报告中的另一个子数据集
- android - 再次返回 Intent,应用程序执行缓慢
- ajax - 加载失败:对预检请求的响应未通过访问控制检查
- oauth - Oauth 访问令牌:如果令牌有 30 天的有效期,我应该每周刷新一次吗?