How can I get optgroup label when select an option in vuejs?

Viewed 1065

I want to get country group name when select option. I've countries with several group like

<template>
    <select id="countries" v-model="country" @change="getCountryGroup($event)">
        <optgroup label="Asia">
            <option value="AF">Afghanistan</option>
            <option value="AM">Armenia</option>
            <option value="AZ">Azerbaijan</option>
            ...
            <option value="BD">Bangaldesh</option>
            ...
        </optgroup>
        <optgroup label="Australia / Oceania">
            <option value="AS">American Samoa</option>
            <option value="AU">Australia</option>
            <option value="CK">Cook Islands</option>
        </optgroup>
        <optgroup label="Africa">
            <option value="DZ">Algeria</option>
            <option value="AM">Angola</option>
            <option value="AZ">Azerbaijan</option>
        </optgroup>
        <optgroup label="South America">
            <option value="AR">Argentina</option>
            <option value="BO">Bolivia</option>
            <option value="BR">Brazil</option>
        </optgroup>
        <optgroup label="North America">
            <option value="US">United States</option>
            <option value="UM">United States Minor Outlying Islands</option>
            <option value="CA">Canada</option>
        </optgroup>
        <optgroup label="Europe">
            <option value="UK">United Kingdom</option>
            <option value="AL">Albania</option>
            <option value="AD">Andorra</option>
        </optgroup>
    </select>
</template>

Suppose when I select Bangladesh then I want to get optgroup name Asia. Here is my vueJs method

getCountryGroup: function(event){
    console.log( event.target.getAttribute('label') );
}
1 Answers

Here are two steps

  1. Get the selected index
  2. Find the selected option
  3. Select the parent element (optgroup) for the selected option
  4. Finally, get the label (Country group)
getCountryGroup: function(event){

    // 1. Get the selected index
    const index = event.target.selectedIndex;

    // 2. Find the selected option
    const option = event.target.options[index];

    // 3. Select the parent element (optgroup) for the selected option
    const optgroup = option.parentElement;

    // 4. Finally, get the label (Country group)
    const countryGroup = optgroup.getAttribute('label');

    console.log(countryGroup);
}

Here is the demo https://codepen.io/maab16/pen/KKKpJba

Related