How to select dropdown item based on value

61 Views

How to select dropdown item based on value

JQuery | Select dropdown item based on value

Change selected option by value on select box with jQuery is common now a days. So let's we have a select element with fruits list, and we need to "select" one of it’s options based on one of it’s values. What we do is just use “selected” selector of jQuery

Let’s say we have the following select element and we need to dynamically select the option with a value of "CS", which would be the Cherries.

 <select id="mySelect">
<option value="">Please Select</option>
<option value="AS">Apples</option>
<option value="BS">Blueberries</option>
<option value="CS">Cherries</option>
<option value="DS">Dewberries</option>
<option value="ES">Eggfruits</option>
</select>

Now below script select "Cherries" in select dropdown

 <script>
$("#myselect option[value='CS']").attr('selected', 'selected');
    
// Or just use...

$("#myselect").val('CS');
</script>

The complete code will...

 <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        $("#myselect option[value='CS']").attr('selected', 'selected');
    
        // Or just use...

        $("#myselect").val('CS');
    </script>
    </head>
    <body>
        <select id="mySelect">
        <option value="">Please Select</option>
        <option value="AS">Apples</option>
        <option value="BS">Blueberries</option>
        <option value="CS">Cherries</option>
        <option value="DS">Dewberries</option>
        <option value="ES">Eggfruits</option>
        </select>
    </body>
</html>

 

Today spacial posts