Sometimes you are in need to limit users of choosing options in your multiple select-boxes, in this short tutorial I'm providing you a solution that prevent users of selecting more than 3 options.
Note: it's optional to you how many option users can select " don't worry :) "
Logic
- Finding our select-box with providing id (can be class also)
- collecting selected options and count them
- if is more than 3 show alert in browser and let user know he/she is only able to choose 3 options
- if they don't care! remove extra selected options value and not sending them to back-end
Code
<select name="tags[]" id="tags" class="form-control" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</select>
Markup
<script type="text/javascript">
$(document).ready(function() {
var arr = new Array();
$("#tags").change(function() {
$(this).find("option:selected")
if ($(this).find("option:selected").length > 3) {
$(this).find("option").removeAttr("selected");
$(this).val(arr);
alert('You can only choose 3!');
}
else {
arr = new Array();
$(this).find("option:selected").each(function(index, item) {
arr.push($(item).val());
});
}
});
});
</script>
JavaScript
Dig in code
$(document).ready(function() {
JavaScript
running our code when page is fully loaded
$("#tags").change(function() {
JavaScript
getting select-box by providing id. in this case id="tags"
$(this).find("option:selected")
JavaScript
finding and counting selected options
if ($(this).find("option:selected").length > 3) {
$(this).find("option").removeAttr("selected");
$(this).val(arr);
alert('You can only choose 3!');
}
JavaScript
if selected options are more than 3 show alert and remove extra values and send first 3 values to back-end only.
else {
arr = new Array();
$(this).find("option:selected").each(function(index, item) {
arr.push($(item).val());
});
}
JavaScript
if user only selected 3 options send those values to back-end.
That's all :).
- Last updated 4 years ago
Be the first to leave a comment.
You must login to leave a comment