简体   繁体   中英

How to limit number of List Box options a user selects in a FORM?

I have a CFFORM that contains a list box, aka a select list. The list box has about 40 choices that users can select before they submit the form.

I would like to limit users to being able to select five or fewer options, and no more.

I am looking for a way to do this in javascript -- maybe a message can pop up if a user selects more than five options.

Or, I am wondering also if there is a way to do it in ColdFusion? I don't see anything like this in my Forta books or CF Bible.

You can add a javascript function like the one below:

function chkSelect(ele) {
      var aSelected = new Array();
      for (var i=0; i<ele.options.length; i++) {
            if (ele.options[i].selected) aSelected.push(ele.options[i].value);
      }
      //alert(aSelected.join(', '));
      if (aSelected.length > 5) {
            alert('Please select 5 or fewer.');
            for (var i=0; i<ele.options.length; i++) {
                  ele.options[i].selected = false;
            }
            ele.focus();
      }
}

The select tag needs to call the function like:

<select onblur="chkSelect(this);"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM