Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select multiselect option limit up to 2

I am using multiselect for different subject's I want to limit the select up to 2 and make the other's disabled in the same way if user deselect, Again the option must be available for the user.

<select multiple="multiple" class="subjects" name="subjects[]" style="float:left;width:205px;" size="5">
  <option value='1'>subject1</option>
  <option value='2'>subject2</option>
  <option value='3'>subject3</option>
  <option value='3'>subject3</option>
</select>

So far I have achieved to deselect only the last option which was selected after 2 and the code is as follow

    /**
     * Make sure the subject's limit is 2
     */
    $(".subjects option").click(function(e){

        if ($(this).parent().val().length > 2) {
            $(this).removeAttr("selected");
        }
    });

Thank you.

like image 468
Prathamesh mhatre Avatar asked Oct 20 '25 16:10

Prathamesh mhatre


2 Answers

Improved jQuery example, notice the (else enable) option, this fixes a bug on previous examples that disabled the select options permanently. Also removed the "Please select only two options." error message when possible. http://jsfiddle.net/c9CkG/25/

jQuery(document).ready(function () {

jQuery("select").on("change", function(){
  var msg = $("#msg");

  var count = 0;

  for (var i = 0; i < this.options.length; i++)
  {
    var option = this.options[i];

    option.selected ? count++ : null;

    if (count > 2)
    {
        option.selected = false;
        option.disabled = true;
        msg.html("Please select only two options.");
    }else{
        option.disabled = false;
        msg.html("");
    }
  }
});

});

like image 186
FriendlyHacker Avatar answered Oct 22 '25 04:10

FriendlyHacker


As an improvment on RobG's answer, you could unselect an option if it makes count > 2.

See: http://jsfiddle.net/c9CkG/3/ for a working example using jQuery.

function checkSelected(el) {
  var msgEl = document.getElementById('msg');
  var count = 0;

  for (var i=0, iLen=el.options.length; i<iLen; i++)

      el.options[i].selected? count++ : null;

      // Deselect the option.
      if (count > 2) {
          el.options[i].selected = false;
          el.options[i].disabled = true;

          msgEl.innerHTML = 'Please select only two options';
      }
}
like image 22
Samuel Parkinson Avatar answered Oct 22 '25 06:10

Samuel Parkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!