将此物料化多选项设置为,选择仅支持最多4个选项。
$(document).on('change', '#selectCountries', function() {
var countriesArr = $(this).val();
if (countriesArr.length > 4) {
alert('only supports maximum 4 countries');
countriesArr = []; // set first 4 elements of array to this variable.
// reload the array to multiselect.
$('#selectCountries').val(countriesArr);
}
});
$('#selectCountries').material_select();
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
<select multiple id="selectCountries">
<option value="0" disabled="" selected=""> Select a Country</option>
<option value="2">United Arab Emirates</option>
<option value="44">Cameroon</option>
<option value="41">U.K</option>
<option value="9">Angola</option>
<option value="45">Chad</option>
<option value="13">Austria</option>
<option value="14">Australia</option>
<option value="20">Belgium</option>
</select>
或任何设置最大限制以实现多选的方法。
答案 0 :(得分:1)
您可以使用slice
获取前4个选定的选项。此外,您可以“刷新”将显示这些值的下拉列表。
唯一的事情就是当你刷新它的下拉列表时,它无法通过代码打开它(就像我发现的那样)。
$(document).on('change', '#selectCountries', function() {
var countriesArr = $(this).val();
if (countriesArr.length > 4) {
alert('only supports maximum 4 countries');
countriesArr = countriesArr.slice(0, 4);
// reload the array to multiselect.
$('#selectCountries').val(countriesArr).material_select();
}
});
$('#selectCountries').material_select();
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.js"></script>
<select multiple id="selectCountries">
<option value="0" disabled="" selected=""> Select a Country</option>
<option value="2">United Arab Emirates</option>
<option value="44">Cameroon</option>
<option value="41">U.K</option>
<option value="9">Angola</option>
<option value="45">Chad</option>
<option value="13">Austria</option>
<option value="14">Australia</option>
<option value="20">Belgium</option>
</select>