Вот полный пример, показывающий HTML-код простой формы и PHP, который позволяет выбирать только до трех вариантов - и дополнительный бонус клиентского JavaScript, объясняющий, как пользователь может сообщить об ошибке до отправки формы.
Вы можете использовать JavaScript, чтобы пользователь не проверял более трех вариантов, но учтите, что проверки на стороне клиента можно легко избежать, поэтому вам все равно придется использовать PHP для проверки на сервере.
HTML
<!doctype html>
<head>
<meta charset="utf-8">
<title>Multiselect example</title>
</head>
<p>Please make a selection below (maximum three options!)</p>
<form method="post">
<select name="selection[]" multiple="multiple">
<!-- Put <option> elements here -->
</select>
<input type="submit">
</form>
<script src="Script.js"></script>
JavaScript (в Script.js):
var formChange = function(e) {
var i,
num = 0,
// Obtain a list of all selected options:
nodeList = this["selection[]"];
// Loop over all options, count how many are selected.
for(i = 0; i < nodeList.length; i++) {
if(nodeList[i].selected) {
num ++;
}
}
if(num > 3) {
alert("Please do not select more than three options");
e.preventDefault();
}
};
// Attach the same function to the change and submit event.
// This will alert the user of more than three selections
// as the fourth is selected, or as the form is submitted.
// ... it will also not allow the form to submit with
// more than three checked boxes.
document.forms[0].addEventListener("change", formChange);
document.forms[0].addEventListener("submit", formChange);
PHP:
if(isset($_POST["selection"])) {
if(count($_POST["selection"]) > 3) {
die("Error: More than three check boxes were checked.");
}
// $_POST["selection"] is an array of the checked values.
}