jQuery | How to Set Dropdown Values for Single and Multiple Selection

The dropdown select box can have single and multiple selections. The muli selection is enabled by adding multiple attribute property. To set the value of the select box in the jQuery use val() method. To set a single value in dropdown pass value as string in val() method and an array of values in case…

By.

•

min read

The dropdown select box can have single and multiple selections. The muli selection is enabled by adding multiple attribute property.

To set the value of the select box in the jQuery use val() method. To set a single value in dropdown pass value as string in val() method and an array of values in case of multi-selection

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Set Single and Multiple Selectbox Values</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

    <script>
        $(function () {

            $("button").click(function () {
                $("#myDropDownSingle").val('5');
                $("#myDropDownMultiple").val(['5', '4', '8']);
            });

        });
    </script>
</head>

<body class="container">

    <p>
        <h5>Single Selection</h5>
        <select id="myDropDownSingle" class="form-control">
            <option value="0">Select Value 0</option>
            <option value="8">Option value 8</option>
            <option value="5">Option value 5</option>
            <option value="4">Option value 4</option>
        </select>
    </p>
    <p>
        <h5>Multiple Selection</h5>
        <select id="myDropDownMultiple" class="form-control" multiple>
            <option value="0">Select Value 0</option>
            <option value="8">Option value 8</option>
            <option value="5">Option value 5</option>
            <option value="4">Option value 4</option>
        </select>
    </p>

    <p>
        <button>Get Value and Text on Button Click</button>
    </p>


</body>

</html>

 

 

 

One response to “jQuery | How to Set Dropdown Values for Single and Multiple Selection”

Leave a Reply

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