Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - How do you limit options selected in a html select box?

I'm using a select tag in a form I'm making that allows multiple selections, but I want to make the maximum amount of selections upto 10. Is this possible using javascript or jquery?

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is some full code for you to use...gotta love the Google AJAX API Playground :-)

Edit 1: Note: this only lets you choose 5 because I didn't feel like copy/pasting another 10 options :-)

<!--
  copyright (c) 2009 Google inc.

  You are free to copy and use this sample.
  License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Sample Select Maximum with jQuery</title>
    <script src="http://www.google.com/jsapi?key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q">    </script>
    <script type="text/javascript">
    google.load("jquery", "1");

    $(document).ready(function() {

      var last_valid_selection = null;

      $('#testbox').change(function(event) {
        if ($(this).val().length > 5) {
          alert('You can only choose 5!');
          $(this).val(last_valid_selection);
        } else {
          last_valid_selection = $(this).val();
        }
      });
    });
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <select multiple id='testbox'>
      <option value='1'>First Option</option>
      <option value='2'>Second Option</option>
      <option value='3'>Third Option</option>
      <option value='4'>Fourth Option</option>
      <option value='5'>Fifth Option</option>
      <option value='6'>Sixth Option</option>
      <option value='7'>Seventh Option</option>
      <option value='8'>Eighth Option</option>
      <option value='9'>Ninth Option</option>
      <option value='10'>Tenth Option</option>
    </select>
  </body>
</html>

Demo

?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...