7

How to Get Attribute Value of the Selected Option using JavaScript

 2 years ago
source link: https://www.codexworld.com/how-to/get-attribute-value-of-the-selected-option-using-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Home  »  How To Guides  »  JavaScript   »   How to Get Attribute Value of the Selected Option using JavaScript

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

Cancel

Comment*

Your Name*

Your Email*

Your Website


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK