Selection Limit

The selection limit feature allows you to control the maximum number of items that can be selected in multiple selects. It's useful for scenarios where you want to limit the user's choices.

Limit of 3 Items

In this example, the user can select a maximum of 3 skills. After reaching the limit, it will not be possible to add more items until one is removed.

View code

HTML

<label for="skills">Selecione até 3 habilidades:</label>
<select id="skills" multiple>
  <option value="javascript">JavaScript</option>
  <option value="python">Python</option>
  <option value="java">Java</option>
  <option value="csharp">C#</option>
  <option value="php">PHP</option>
  <option value="ruby">Ruby</option>
  <option value="go">Go</option>
  <option value="rust">Rust</option>
  <option value="swift">Swift</option>
  <option value="kotlin">Kotlin</option>
</select>

JavaScript

new VanillaSmartSelectClass('#skills', {
  searchable: true,
  maximumSelectionLength: 3
});
💡 Tip: When the limit is reached, a message is displayed automatically and unselected items are temporarily disabled.

Limit of 2 Items

Example with a more restrictive limit of only 2 frameworks. Useful when you want to force the user to choose their main preferences.

View code

HTML

<label for="frameworks">Selecione até 2 frameworks:</label>
<select id="frameworks" multiple>
  <option value="react">React</option>
  <option value="vue">Vue.js</option>
  <option value="angular">Angular</option>
  <option value="svelte">Svelte</option>
  <option value="ember">Ember.js</option>
  <option value="backbone">Backbone.js</option>
</select>

JavaScript

new VanillaSmartSelectClass('#frameworks', {
  searchable: true,
  maximumSelectionLength: 2
});

Limit of 5 Items with Groups

The selection limit works perfectly with optgroups. In this example, you can select up to 5 countries from different continents.

View code

HTML

<label for="countries">Selecione até 5 países:</label>
<select id="countries" multiple>
  <optgroup label="América do Sul">
    <option value="br">Brasil</option>
    <option value="ar">Argentina</option>
    <option value="cl">Chile</option>
    <option value="co">Colômbia</option>
    <option value="pe">Peru</option>
  </optgroup>
  <optgroup label="Europa">
    <option value="pt">Portugal</option>
    <option value="es">Espanha</option>
    <option value="fr">França</option>
    <option value="it">Itália</option>
    <option value="de">Alemanha</option>
  </optgroup>
  <optgroup label="Ásia">
    <option value="jp">Japão</option>
    <option value="cn">China</option>
    <option value="kr">Coreia do Sul</option>
    <option value="in">Índia</option>
  </optgroup>
</select>

JavaScript

new VanillaSmartSelectClass('#countries', {
  searchable: true,
  maximumSelectionLength: 5
});

No Limit (Default)

By default, there is no selection limit. You can explicitly set maximumSelectionLength: 0 or simply omit the configuration to allow unlimited selection.

View code

HTML

<label for="colors">Selecione quantas cores desejar:</label>
<select id="colors" multiple>
  <option value="red">Vermelho</option>
  <option value="blue">Azul</option>
  <option value="green">Verde</option>
  <option value="yellow">Amarelo</option>
  <option value="purple">Roxo</option>
  <option value="orange">Laranja</option>
  <option value="pink">Rosa</option>
  <option value="brown">Marrom</option>
  <option value="black">Preto</option>
  <option value="white">Branco</option>
</select>

JavaScript

new VanillaSmartSelectClass('#colors', {
  searchable: true,
  maximumSelectionLength: 0  // 0 = unlimited (default)
});

Monitoring Limit Events

You can listen to the vs:selectionLimitReached event to execute custom actions when the limit is reached. The event provides details about the maximum limit and the displayed message.

Event Log:
Events will appear here...
View code

HTML

<label for="tags">Selecione até 4 tags:</label>
<select id="tags" multiple>
  <option value="tag1">Design</option>
  <option value="tag2">Desenvolvimento</option>
  <option value="tag3">Marketing</option>
  <option value="tag4">Vendas</option>
  <option value="tag5">Suporte</option>
  <option value="tag6">Administração</option>
  <option value="tag7">Recursos Humanos</option>
  <option value="tag8">Financeiro</option>
</select>

<div id="event-log"></div>

JavaScript

const tagsElement = document.getElementById('tags');
const eventLog = document.getElementById('event-log');

new VanillaSmartSelectClass('#tags', {
  searchable: true,
  maximumSelectionLength: 4
});

// Listen to selection limit reached event
tagsElement.addEventListener('vs:selectionLimitReached', (e) => {
  const timestamp = new Date().toLocaleTimeString();
  const logEntry = document.createElement('div');
  logEntry.style.marginBottom = '8px';
  logEntry.innerHTML = `
    <strong style="color: #856404;">[${timestamp}] Limit Reached!</strong><br>
    <span style="color: #666;">Maximum: ${e.detail.maximum} | Message: "${e.detail.message}"</span>
  `;
  eventLog.insertBefore(logEntry, eventLog.firstChild);
});

// Also log select events
tagsElement.addEventListener('vs:select', (e) => {
  const timestamp = new Date().toLocaleTimeString();
  const logEntry = document.createElement('div');
  logEntry.style.marginBottom = '8px';
  logEntry.innerHTML = `
    <strong style="color: #28a745;">[${timestamp}] Selected:</strong>
    <span style="color: #666;">${e.detail.data.text}</span>
  `;
  eventLog.insertBefore(logEntry, eventLog.firstChild);
});
✅ Custom Event: The vs:selectionLimitReached event contains e.detail.maximum (maximum number allowed) and e.detail.message (message displayed to the user).

API Configuration

Available configurations for selection limit control:

Property Type Default Description
maximumSelectionLength Number 0 Maximum number of items that can be selected. Use 0 for unlimited.

Related Events

Events fired during selection limit control:

Event Description Event Data
vs:selectionLimitReached Fired when the user tries to select more items than the allowed limit e.detail.maximum - maximum number allowed
e.detail.message - displayed message
vs:select Fired when an item is selected (before the limit is reached) e.detail.data - selected item data
vs:unselect Fired when an item is removed from selection e.detail.data - removed item data

Personalização de Mensagens (i18n)

Você pode personalizar a mensagem exibida quando o limite é atingido através das configurações de internacionalização:

JavaScript

new VanillaSmartSelectClass('#element', {
  maximumSelectionLength: 3,
  language: {
    maximumSelected: function(args) {
      return 'Você só pode selecionar ' + args.maximum + ' itens';
    }
  }
});

// Ou usando texto simples
new VanillaSmartSelectClass('#element', {
  maximumSelectionLength: 5,
  language: {
    maximumSelected: 'Limite de 5 itens atingido!'
  }
});
💡 Multilíngue: Use a configuração language para adaptar mensagens ao idioma do seu aplicativo. Veja a página de internacionalização para mais detalhes.

Common Use Cases

📋 Practical Applications:
  • Survey Forms: Limit number of filters or selected categories
  • Skills Selection: Ask users to choose their main skills (e.g., top 3)
  • Preferences: Limit choices in user settings or preferences
  • Voting: Allow voting on multiple options up to a specific limit
  • Tags/Categories: Avoid tag overload on content or products
  • Resource Allocation: Limit how many resources can be assigned to a task

Best Practices

✅ Recommendations:
  • Communicate the Limit: Always inform the limit in the label or placeholder (e.g., "Select up to 3 items")
  • Visual Feedback: The library already provides feedback, but you can add custom styles
  • Custom Events: Use vs:selectionLimitReached to show additional warnings or suggestions
  • Reasonable Limits: Choose limits that make sense for the context (avoid too restrictive limits)
  • Clear Messages: Customize error messages to be helpful and friendly
  • Validation: Combine with form validation to ensure the minimum is also respected
← Pagination Validation →