<!DOCTYPE html>
<
html
>
<
head
>
<
style
>
body {
text-align: center;
}
p {
font-size: 25px;
font-weight: bold;
}
select {
display: block;
margin: 0 auto;
}
button {
margin-top: 1rem;
cursor: pointer;
}
</
style
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>GeeksforGeeks</
h1
>
<
p
>jQuery - Restrict the Number of Selected
Options in a Multi-Select Input Field</
p
>
<
select
id
=
"dropdown"
multiple>
<
option
value
=
"Geek 1"
>Geek 1</
option
>
<
option
value
=
"Geek 2"
>Geek 2</
option
>
<
option
value
=
"Geek 3"
>Geek 3</
option
>
<
option
value
=
"Geek 4"
>Geek 4</
option
>
</
select
>
<
button
class
=
"check-multi-select"
>
Click me to check if dropdown is within the limit
</
button
>
<
script
src
=
</
script
>
<
script
type
=
"text/javascript"
>
$(document).ready(function () {
$(".check-multi-select").click(function () {
// Set the maximum number of selections allowed
let maxSelections = 2;
let selectedOptions = $("#dropdown").find('option:selected');
// Reset disabled options
$("#dropdown option").prop("disabled", false);
if (selectedOptions.length > maxSelections) {
// Disable excess selections
selectedOptions.slice(maxSelections).prop("disabled", true);
alert("You can only select up to " + maxSelections + " options.");
} else {
alert("You are within the selection limit.");
}
});
});
</
script
>
</
body
>
</
html
>