限制多重选择HTML PHP的数量

时间:2011-10-31 11:21:51

标签: php html count limit multi-select

如何限制多重选择的数量?就像我希望用户从多选中选择最多3个元素。如果选择超过3个,那么我会给他一个错误......

5 个答案:

答案 0 :(得分:3)

这是一个完整的示例,显示了一个简单表单的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.
}

答案 1 :(得分:1)

PHP中的multiselect元素返回一个数组,因此只需要将返回数组的count()与您想要允许的最大值进行比较,如果计数超过限制就会产生某种错误(抛出一个异常,触发错误等)。

答案 2 :(得分:1)

如果您想在服务器端执行此操作,请查看count()功能。如,

HTML:

<form ...>
  <select name="options[]" multiple="multiple">
    <!-- options here ... -->
  </select>
  ...
</form>

PHP:

<?php

if (isset($_POST['options']) && count($_POST['options']) <= 3) {
    // OK
} else {
    // Not OK
}

?>

答案 3 :(得分:0)

看看这个js函数,假设你的多选对象是“muSelect”

function checkSelected() {
 var i;
  var count = 0;
  for (i=0; i<muSelect.options.length; i++) {
    if (muSelect.options[i].selected) {
      count++;
    }
     if (count > 3) {
        alert("cant select more than three options";
        // any  other additionnal processing
      }
  }
}

然后您可以将此功能添加为onClick事件

答案 4 :(得分:0)

我知道这是一个老问题,但是如果有人现在正在尝试做同样的事情并且寻找答案最好为这个答案写一个当前的答案。目前最好的方法是使用AJAX(只要我知道):

HTML:form.html

    <form id="myForm" action="validate.php?q=1">
        <select name="options[]" multiple="multiple">
        <!-- options here ... -->
        </select>
        ...
    </form>

PHP:validate.php

    <?php
        switch($_REQUEST['q']){
            case 0:
                if(isset($_REQUEST['options']) && count($_REQUEST['options']) <=3){
                    echo true;
                }else{
                    echo false;
                }
            break;
            case 1:
                if(isset($_POST['options']) && !empty($_POST['options'])){
                    if(count($_POST['options']) <= 3){
                        //OK
                    }else{
                        //NOT OK
                    }
                }
            break;
        }
    ?>

JavaScript(jQuery):script.js

    var form = $("#myForm");
    var options = $("#select_menu option")
    var selected = [];

    $(options).each(function(key,option){
        if(option.selected){
            selected[key] = option;
        }
    });

    $.ajax({
        url: "validate.php",
        method: "GET",
        data: {
            options: selected,
            q: 0
        },
        success: function(Response){
            if(Response === true){
                //OK
            }else{
                //NOT OK
            }
        }
    });

如果我在某个地方有错误,请纠正我。