Last active
December 20, 2023 16:55
-
-
Save dantetesta/6b684be9d3e121fde1ddb3c3f5130d78 to your computer and use it in GitHub Desktop.
Limite de seleção selectbox.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).ready(function() { | |
// Função para adicionar o listener de mudança em um select box | |
function setupLimitForSelectBox(selectBoxId, limitFieldName) { | |
jQuery(selectBoxId).on('change', function() { | |
var limit = parseInt(jQuery('input[name="' + limitFieldName + '"]').val(), 10); | |
var selectedOptions = jQuery(this).find('option:selected'); | |
if (selectedOptions.length > limit) { | |
// Reverter a última seleção | |
selectedOptions.each(function(index) { | |
if (index >= limit) { | |
jQuery(this).prop('selected', false); | |
} | |
}); | |
// Opcional: Mostrar uma mensagem ao usuário | |
alert('Você pode selecionar no máximo ' + limit + ' categorias.'); | |
} | |
}); | |
} | |
// Configuração para cada select box | |
setupLimitForSelectBox('#categoria1', 'limite-1'); | |
setupLimitForSelectBox('#categoria2', 'limite-2'); | |
setupLimitForSelectBox('#categoria3', 'limite-3'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment