Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Multiselect Limit

Tags:

html

select

limit

Is it possible to set limit to multipleselect?

Below is an example code where user can select more than 1 value.

<select multiple="multiple" name="choose">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
</select>

But, how to limit user to select not more than 3 value. Any idea?

like image 932
Hafizul Amri Avatar asked Nov 09 '10 15:11

Hafizul Amri


People also ask

How do I allow multiple selections in HTML?

For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

What is multiselect?

Noun. multiselection (uncountable) (computing, graphical user interface) Multiple selection; the ability to have more than one item selected at the same time.


2 Answers

You can use jQuery

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });
like image 73
Alex Rashkov Avatar answered Sep 22 '22 04:09

Alex Rashkov


You would do this via javascript on the client side, and then add a check on the server side as well in case the client has disabled javascript.

Here is some basic client side code to give you an idea:

<html>
    <body>
        <form onsubmit="validate()">
            <select multiple="multiple" id="choose" name="choose"> 
                <option value="1">Value 1</option> 
                <option value="2">Value 2</option> 
                <option value="3">Value 3</option> 
                <option value="4">Value 4</option> 
                <option value="5">Value 5</option> 
                <option value="6">Value 6</option> 
            </select><br>
            <input type="submit">
        </form>
        <script>
        function validate()
        {
            var selectChoose = document.getElementById('choose');
            var maxOptions = 2;
            var optionCount = 0;
            for (var i = 0; i < selectChoose.length; i++) {
                if (selectChoose[i].selected) {
                    optionCount++;
                    if (optionCount > maxOptions) {
                        alert("validation failed, not submitting")
                        return false;
                    }
                }
            }
            return true;
        }
        </script>
    </body>
</html>
like image 22
D'Arcy Rittich Avatar answered Sep 23 '22 04:09

D'Arcy Rittich