Select tag presents has got a long list of options. How can I make sure that at least 2 options are selected by the user? The first option is required, I also need the second to be required.
Here's the code:
<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>
Your select tag presents is an array already. Check the array length to make sure you have at least 2 options selected. When the form is submitted, try this on your php page:
$presents = $_POST['presents'];
if (count($presents) >= 2) {
// Here you are sure that you have at least two options selected.
// Do whatever you wish here.
}
Or else, you can also get the same result with 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);
})