How To Get Selected Option Attribute By Jquery

In this article, We learn how to get the selected option attributes by jquery.

Step 1: Create a select field in HTML.

<!DOCTYPE html>
<html>
    <head>
        <title>
            Get Option Attribute
        </title>
    </head>
    <body>
        <select id="get_attribute">
            <option attr="option-1">option 1</option>
            <option attr="option-2">option 2</option>
            <option attr="option-3">option 3</option>
        </select>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    </body>
</html>

Step 2: User change event to get attribute when selecting option change.

$(document).ready(function(){
    $(document).on('change','#get_attribute',function(){                
    });
});

Step 3: User below js to get selected option attribute.

$(document).on('change','#get_attribute',function(){
    var attr = $('option:selected', this).attr("attr");
});

Here is the full code:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Get Option Attribute
        </title>
    </head>
    <body>
        <select id="get_attribute">
            <option attr="option-1">option 1</option>
            <option attr="option-2">option 2</option>
            <option attr="option-3">option 3</option>
        </select>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $(document).on('change','#get_attribute',function(){
                    var attr = $('option:selected', this).attr("attr");
                    alert(attr);
                });
            });
        </script>
    </body>
</html>

Here is the result:

Thanks

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories