AjaxJavaScriptjQuery

How to get value of selected option in Jquery

To get the value of selected option in jquery we can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

Below is the html code for my dropdown

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Selected Option Value</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head> 
<body>
    <form>
        <label>Select state:</label>
        <select class="state">
            <option value="bihar">Bihar</option>
            <option value="delhi">Delhi</option>
            <option value="punjab">Punjab</option>
        </select>
    </form>
</body>
</html>

Below code is for onchange script, learn more about onChange from here

<script>
$(document).on('change','.state',function(){
                var state = $(this).children("option:selected").val();
         alert(state);
});
</script>

We have use $(document).on change to get dynamic value, for example if you pass dynamic value to your loop then you must have to use $(document).on change on order to get those value.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Selected Option Value</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).on('change','.state',function(){
        var state = $(this).children("option:selected").val();
        alert(state);
    });
</script>
</head> 
<body>
    <form>
        <label>Select state:</label>
        <select class="state">
            <option value="bihar">Bihar</option>
            <option value="delhi">Delhi</option>
            <option value="punjab">Punjab</option>
        </select>
    </form>
</body>
</html>

I hope you like the above the blog,Please rate me 5 so that I can keep posting the content like above.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Back to top button