How to Limit Options Selected in a HTML Select Box

How can I limit the options in an HTML select dropdown?

You can simply add this into your tag:

<select onmousedown="if(this.options.length>5){this.size=5;}"> 
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>

How do you limit options selected in a html select box?

Here is some full code for you to use...gotta love the Google AJAX API Playground :-)

Edit 1: Note: this only lets you choose 5 because I didn't feel like copy/pasting another 10 options :-)

<!--
copyright (c) 2009 Google inc.

You are free to copy and use this sample.
License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Sample Select Maximum with jQuery</title>
<script src="http://www.google.com/jsapi?key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q"> </script>
<script type="text/javascript">
google.load("jquery", "1");

$(document).ready(function() {

var last_valid_selection = null;

$('#testbox').change(function(event) {
if ($(this).val().length > 5) {
alert('You can only choose 5!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
});
});
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<select multiple id='testbox'>
<option value='1'>First Option</option>
<option value='2'>Second Option</option>
<option value='3'>Third Option</option>
<option value='4'>Fourth Option</option>
<option value='5'>Fifth Option</option>
<option value='6'>Sixth Option</option>
<option value='7'>Seventh Option</option>
<option value='8'>Eighth Option</option>
<option value='9'>Ninth Option</option>
<option value='10'>Tenth Option</option>
</select>
</body>
</html>

Demo

Multiple Select limit number of selection

Try this...

Check length and deselect after reach maximum select

<select id="userRequest_activity" required name="activity[]" class="multiselect form-control" multiple="multiple">
<option value="2">Bungee Jumping</option>
<option value="3">Camping</option>
<option value="5">Mountain Biking</option>
<option value="6">Rappelling</option>
<option value="7">Rock Climbing / Bouldering</option>
<option value="8">Skiing</option>
<option value="10">Wild Life (Safari)</option>
<option value="11">Canoeing & Kayaking</option>
<option value="12">Rafting</option>
<option value="13">Sailing</option>
<option value="14">Scuba Diving</option>
<option value="15">Snorkeling</option>
<option value="16">Surfing</option>
<option value="18">Hang Gliding</option>
<option value="19">Hot-air Ballooning</option>
<option value="20">Micro-light Aircrafts</option>
<option value="21">Paragliding</option>
<option value="22">Paramotoring</option>
<option value="23">Parasailing</option>
<option value="24">Skydiving / Parachuting</option>
<option value="25">Zip-line / Flying Fox</option>
<option value="26">Caving</option>
<option value="27">Cycling</option>
<option value="28">Fishing & Angling</option>
<option value="29">Motorbike trips</option>
<option value="30">Nature Walks</option>
<option value="31">Road Trips</option>
<option value="32">Zorbing</option>
<option value="33">Trekking Hiking and Mountaineering</option>
<option value="34">Backpacking</option>
<option value="61">Water</option>
</select>

<script type="text/javascript">

$(document).ready(function() {

var last_valid_selection = null;

$('#userRequest_activity').change(function(event) {

if ($(this).val().length > 3) {

$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
});
});
</script>

DEMO:http://jsfiddle.net/9c3sevuv/

How to limit amount of selected in custom select menu in javascript?

Just count selected items, create variable let count = 0;, add count increase on selection add check on count before selecting.

class CustomSelect {
constructor(originalSelect) {
this.originalSelect = originalSelect;
this.customSelect = document.createElement("div");
this.customSelect.classList.add("select");

let count = 0;

this.originalSelect.querySelectorAll("option").forEach((optionElement) => {
const itemElement = document.createElement("div");

itemElement.classList.add("select__item");
itemElement.textContent = optionElement.textContent;
this.customSelect.appendChild(itemElement);

if (optionElement.selected) {
this._select(itemElement);
}

itemElement.addEventListener("click", () => {
if (
this.originalSelect.multiple &&
itemElement.classList.contains("select__item--selected")
) {
this._deselect(itemElement);
count--;
} else if (count < 2) {
this._select(itemElement);
count++;
}
});
});

this.originalSelect.insertAdjacentElement("afterend", this.customSelect);
this.originalSelect.style.display = "none";
}

_select(itemElement) {
const index = Array.from(this.customSelect.children).indexOf(itemElement);

if (!this.originalSelect.multiple) {
this.customSelect.querySelectorAll(".select__item").forEach((el) => {
el.classList.remove("select__item--selected");
});
}

this.originalSelect.querySelectorAll("option")[index].selected = true;
itemElement.classList.add("select__item--selected");
}

_deselect(itemElement) {
const index = Array.from(this.customSelect.children).indexOf(itemElement);

this.originalSelect.querySelectorAll("option")[index].selected = false;
itemElement.classList.remove("select__item--selected");
}
}

document.querySelectorAll(".custom-select").forEach((selectElement) => {
new CustomSelect(selectElement);
});
.select {
display: grid;
grid-template-columns: repeat(3, 1fr);
max-width: 300px;
gap: 1px;
}

.select__item {
padding: 10px;
cursor: pointer;
font-family: "Heebo", sans-serif;
text-align: center;
border-radius: 3px;
background: #eeeeee;
transition: background 0.1s;
}

.select__item--selected {
background: #009578;
color: #ffffff;
}
<select name="language" class="custom-select" multiple>
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JavaScript</option>
<option value="python">Python</option>
<option value="sql">SQL</option>
<option value="kotlin">Kotlin</option>
</select>

Limiting options in select dropdown to a specific number

HTML Code

<select onmousedown="if(this.options.length>15){this.size=15;}" onchange='this.size=0;' onblur="this.size=0;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
</select>

Please check the working fiddle:
Demo

How to limit options in a select based on another option selection

I've created a quick function to help you out, there may be a neater way to do this, but it does the job quite nicely!

Onchange of the element #semester_credits I grab the value (number of semesters credits and then loop over the next select box and remove the ones that have a higher value that the chosen one, I use a global var to cache the removed options in case the user changes their minds and we need to add them back in.

$(function () {

var savedOpts = "";
$('#semester_credits').change(function() {
//Add all options back in;
if( savedOpts ) {
$('#skipped_total_credits').append(savedOpts);
savedOpts = "";
}

//Return false if blank option chosen;
if( $(this).val() === "0" )
return false;

var chosenCreds = parseInt($(this).val());
$('#skipped_total_credits option').each(function() {
var thisCred = parseInt($(this).val());
if(thisCred > chosenCreds) {
//Remove
savedOpts += $(this)[0].outerHTML;
$(this).remove();
}
});
});

Here an updated fiddle

p.s the example Kai Hartmann suggests is also a nice way to achieve this.

how to select limit number of options in multiple select plugin?

EDIT :

There working jsFiddle example with multi-select plugin

var limit = 3;

var $multiSel = $("select").multipleSelect({
placeholder: "Here is the placeholder",
width: 200,
filter: true,
selectAll: false,
onClick: function(view) {
var $checkboxes = $multiSel.next().find("input[type='checkbox']").not(":checked");
var selectedLen = $multiSel.multipleSelect('getSelects').length;
if (selectedLen >= limit) {
$checkboxes.prop("disabled", true);
} else {
$checkboxes.prop("disabled", false);
}
}
});

Using jQuery Chosen to limit options based on a previous selection

I was able to get this working and wanted to be sure to post the answer for anyone else that may want to implement something similar in the future. Thank you to everyone for your help!

jQuery('#industrySelect').chosen().change(function() {  var industrySelected = jQuery(this).chosen().val();  var $verticalMarket = jQuery('select#verticalMarketSelect');  var $verticalMarketHolder = jQuery('select#verticalMarketHolder');  if (industrySelected == null) {    $verticalMarket.empty();  } else {    $verticalMarket.find('option.existing').removeClass('existing');    jQuery.each(industrySelected, function(index, value) {      $verticalMarket.find('[industry="' + value + '"]').addClass('existing');    });    $verticalMarket.find('option').not('.existing').remove();    jQuery.each(industrySelected, function(index, value) {      var option = $verticalMarketHolder.find('[industry="' + value + '"]').clone();      var existingOptions = $verticalMarket.find('[industry="' + value + '"]');      if (existingOptions.length == 0) {        $verticalMarket.append(option);      }    });  }  jQuery('#verticalMarketSelect').trigger('chosen:updated');});jQuery(function() {  jQuery('#industrySelect').trigger('change');});
<div class="wrapper">  <select id="industrySelect" class="chosen-industry-select" data-placeholder="select industry" multiple>    <option value=""></option>    <option value="1">Business</option>    <option value="2">Education</option>    <option value="3">Healthcare</option>  </select>
<select id="verticalMarketSelect" class="chosen-verticalMarket-select" data-placeholder="select vertical market" multiple> <option value=""></option> <option value="1" industryValue="1">Retail</option> <option value="2" industryValue="1">Construction</option> <option value="3" industryValue="1">Automotive</option> <option value="4" industryValue="2">University</option> <option value="5" industryValue="2">Elementary School</option> <option value="6" industryValue="2">High School</option> <option value="7" industryValue="3">Hospital</option> <option value="8" industryValue="3">Doctor Office</option> <option value="9" industryValue="3">Dentist</option> </select></div>


Related Topics



Leave a reply



Submit