jquery dropdown code example

Example 1: how to get the value of dropdown in jquery

BY LOVE
$('#ddlName option:selected').val();

Example 2: set dropdown in jquery

$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

Example 3: jquery dropdown select

$('select>option:eq(3)').prop('selected', true);

Example 4: set dropdown in jquery

$('select[name^="salesrep"] option:selected').attr("selected",null);

Example 5: dropdown menu jquery

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Dropdown Example</h2>
  <p>The data-toggle="dropdown" attribute is used to open the dropdown menu.</p>
  <div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" id="menu1" type="button" data-toggle="dropdown">Dropdown Example
    <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">HTML</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">CSS</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">JavaScript</a></li>
      <li role="presentation" class="divider"></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">About Us</a></li>    
    </ul>
  </div>
</div>

</body>
</html>

Example 6: select 2 dropdown

$('#element').select2({
    placeholder: 'Select a option',
    minimumInputLength: 3,
    ajax: {
        url: route('api.fetch-options'),
        dataType: 'json',
        type: 'GET',
        quietMillis: 50,
        data: function (params) {
            return {
                visitor_name: params.term
            }
        },
        processResults({ data }) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.name,
                        id: item.id,
                    }
                })
            }
        }
    }
}).change(() => {
	// perform some action on change
});

Tags:

Misc Example