How To Make Option Selected In Jquery

In this blog post, we will learn how to make an option selected in a dropdown (select) element using jQuery. This can be useful for setting the default value of a dropdown, or for changing the value dynamically based on user input.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of HTML and jQuery. You should also have the latest version of jQuery included in your project.

HTML Setup

First, let’s create a simple HTML dropdown (select) element with some options. In this example, we will create a dropdown for selecting a fruit.

    <select id="fruit-select">
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
        <option value="cherry">Cherry</option>
        <option value="grape">Grape</option>
    </select>
    

jQuery Method 1: Using the ‘val()’ function

One way to make an option selected in jQuery is to use the val() function. By passing the value of the option you want to select as an argument, jQuery will make that option selected.

For example, let’s say we want to make the “Banana” option selected by default. We can achieve this with the following jQuery code:

    $(document).ready(function() {
        $('#fruit-select').val('banana');
    });
    

jQuery Method 2: Using the ‘prop()’ function

Another way to make an option selected in jQuery is to use the prop() function. This method allows you to set the ‘selected’ property of the option element directly.

Using the same example as before, let’s make the “Banana” option selected by default using the prop() function:

    $(document).ready(function() {
        $('#fruit-select option[value="banana"]').prop('selected', true);
    });
    

Conclusion

In this blog post, we learned two different jQuery methods to make an option selected in a dropdown (select) element: using the val() function and the prop() function. Both methods are easy to implement and can be used to set default values or change values dynamically based on user input.

Now that you know how to make an option selected in jQuery, you can create more interactive and user-friendly web applications. Happy coding!