首页 > 解决方案 > 在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)
}

标签: javascripthtml

解决方案


您可以通过访问 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>


推荐阅读