javascript - 在javascript中获取选项名称
问题描述
嗨,我有一个 HTML 形式的选择标签
我想在更改时选择选项名称(属性)
我能做些什么?
我在谷歌搜索,但我没有找到
用 Django 编写 HTML 表单
我的代码:
<form action="{% url 'busi:add_business' %}" method="POST">
{% csrf_token %} {{business_form.as_p}}
<select name="" id="provinses">
</select>
<button type="submit">افزودن</button>
</form>
var provinces = [{
"id": 1,
"name": "آذربایجان شرقی",
"slug": "آذربایجان-شرقی"
},
{
"id": 2,
"name": "آذربایجان غربی",
"slug": "آذربایجان-غربی"
},
{
"id": 3,
"name": "اردبیل",
"slug": "اردبیل"
},
]
for (var i = 0; i < provinces.length; i++) {
var node = document.createElement("option");
var textnode = document.createTextNode(provinces[i].name);
node.appendChild(textnode);
node.setAttribute("name", provinces[i].id)
document.getElementById("provinses").appendChild(node);
}
const selectElement = document.querySelector('#provinses');
selectElement.addEventListener('change', optionName)
function optionName(e) {
var name = this.name;
console.log(name)
}
解决方案
您可以通过访问 select 的value
.
var provinces = [{
"id": 1,
"name": "آذربایجان شرقی",
"slug": "آذربایجان-شرقی"
},
{
"id": 2,
"name": "آذربایجان غربی",
"slug": "آذربایجان-غربی"
},
{
"id": 3,
"name": "اردبیل",
"slug": "اردبیل"
},
]
for (var i = 0; i < provinces.length; i++) {
var node = document.createElement("option");
var textnode = document.createTextNode(provinces[i].name);
node.setAttribute("name", provinces[i].id)
node.appendChild(textnode);
document.getElementById("provinses").appendChild(node);
}
const selectElement = document.querySelector('#provinses');
selectElement.addEventListener('change', optionName)
function optionName(e) {
var opts = this.options;
console.log('Selected id', opts[this.selectedIndex].getAttribute('name'));
console.log('Selected value', this.value);
}
<select id="provinses"></select>
推荐阅读
- css - 在 Bootstrap 4 选项卡中对齐关闭图标
- java - Mopub Android 设置:“找不到 moat-mobile-app-kit”
- google-drive-api - 您可以为 Google Drive 构建数据库应用程序吗?
- scala - 如何通过 Spark 上的 Apache Livy 执行一个 jar 打包的 scala 程序,该程序直接响应客户端请求的结果?
- php - 如何在 PHP 中使用正则表达式匹配这种类似数组的表示法?
- android - Kotlin/Android - 只能检查一个 ToggleButton
- shell - 运行 traceroute 和 traceroute6 的最短 shell 代码
- r - 按来自另一个矩阵的列名对矩阵进行排序
- python-3.x - AttributeError:模块“skimage.measure”没有属性“marching_cubes”
- azure - 如何将 VSTS(又名 Azure DevOps)帐户绑定到 Azure 订阅