<option> 需要<select>多个



Select标记presents有一长串选项。如何确保用户至少选择了2个选项?第一个选项是必需的,我也需要第二个选项。

这是代码:

<select name="presents[]" id="presents" class="vv-select2-multiple" multiple required>
<?php foreach(get_from_group('person', 'any', -1, ['tipo' => 'member']) as $member):?>
<option value="<?= $member->ID ?>" <?php selected(get_user_person()->ID, $member->ID)?> required><?= $member->post_title; ?></option>
<?php endforeach;?>
</select>

您的选择标记presents已经是一个数组。检查阵列长度以确保至少选择了2个选项。提交表单后,请在您的php页面上尝试此操作:

$presents = $_POST['presents'];
if (count($presents) >= 2) {
// Here you are sure that you have at least two options selected.
// Do whatever you wish here. 
}

否则,您也可以使用jquery获得相同的结果。

function checkCount() {
if($('#presents option').is(':selected')) {
count = $('#presents option:selected').length;
console.log(count);
if (count >= 2) {
console.log('Selected option are greater than or equal to 2');
} else {
console.log('Selected options are less than two');
}
} else {
console.log('No options are selected!!!')
}
}
$(document).ready(function () {
checkCount();
$('#presents').on('change', checkCount);
})

在线试用。

最新更新