How to Get Attribute Value of the Selected Option using JavaScript

Mostly, the value attribute of the option tag is used in the select box. Besides the option value, custom attributes can be defined in the option tag of the select dropdown. You can also get the custom attribute value from the select box with JavaScript. The attribute value of the selected option can be retrieved using JavaScript easily.

In this example code snippet, we will show you how to get the attribute value of the selected option in JavaScript.

The following select box dropdown holds the country list. The ID is defined in the value attribute and the country code is defined in the country_code.

<select id="country_select"> 
	<option value="1" country_code="US">United States</option>
	<option value="2" country_code="UK">United Kingdom</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

The following code can be used to get the country_code attribute value from the selected option of the country dropdown list using JavaScript.

var country_select = document.querySelector("#country_select");
var country_code = country_select.options[country_select.selectedIndex].getAttribute('country_code');

console.log(country_code); //It will output US/UK based on the selected option

Leave a reply

keyboard_double_arrow_up