-2

Hi i have a select tag in HTML form

I wanna get option name (attribute) when select on change

What can I do?

i very search in google but i not found

HTML form write with Django

my code:

<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)
}
Ali Rahmani
  • 41
  • 1
  • 4
  • you know how to set attribute `name`. so basically the same you can do just with get attribute name. You can find it in google how to do it. Other thing is to bind select onchange event – demo Aug 29 '21 at 12:54
  • [option elements](https://html.spec.whatwg.org/multipage/form-elements.html#the-option-element) don't have names. They have `value`s. The name belongs to the `select` element. – Quentin Aug 29 '21 at 12:55
  • Does this answer your question? [Get selected value in dropdown list using JavaScript](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Rifky Niyas Aug 29 '21 at 12:57

1 Answers1

-1

You can get it by accessing select's 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>
capchuck
  • 461
  • 2
  • 8