我有多个选择标签,每个选项都有一个数值 当它们的值超过定义的值时,我试图限制所选的选择 现在,它仅适用于单个选项,而不适用于选择多个选项 这是我的代码:
// Users table
class User
{
int Id;
string FullName;
string Email;
string PhoneNumber;
}
// Persons table
class Person
{
int Id;
int UserId; // Users table
int CompanyId; // Companies table
}
// Companies table
class Company
{
int Id;
string Name;
}
$(document).ready(function() {
var last_selection = null;
var num = 4;
$('select#multi_limit').change(function(event) {
if ($(this).val() > num) {
$(this).val(last_selection);
alert('You can select options which their values dont exceeds 4 ');
}
else {
last_selection = $(this).val();
}
});
});
答案 0 :(得分:2)
您需要比较长度而不是val()
,因此val().length
应该是您要使用的长度。并且您需要在此处将限制设置为3而不是4。
$(document).ready(function() {
var last_selection = null;
var num = 6;
$('select#multi_limit').change(function(event) {
let sum = $(this).val().reduce((a,b) => +a + +b , 0);
console.log('sum',sum);
if ( sum > num) {
$(this).val(last_selection);
alert('You can select upto 3 options only');
} else {
last_selection = $(this).val();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="multi_limit" required name="activity[]" class="multiselect form-control" multiple="multiple">
<option value="2">Printers</option>
<option value="3">Screens</option>
<option value="5">Keyboards</option>
<option value="6">Mouses</option>
<option value="7">Computers</option>
</select>
按照注释中的说明进行更新,您需要总和,而可以添加以首先获取总和。 .reduce((a,b) => a+b , 0)
答案 1 :(得分:0)
您可以像下面那样检查选定的长度。
$(document).ready(function() {
var last_selection = null;
var num = 4;
$('#multi_limit').change(function(event) {
if ($("#multi_limit :selected").length > num) {
alert('You can select options which their values dont exceeds 4');
} else {
last_selection = $(this).val();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="multi_limit" required name="activity[]" class="multiselect form-control" multiple="multiple">
<option value="2">Printers</option>
<option value="3">Screens</option>
<option value="5">Keyboards</option>
<option value="6">Mouses</option>
<option value="7">Computers</option>
</select>