Search code examples
jqueryselectlimit

jQuery Chosen: how to limit the number of selected values and provide an error message


I'm in the process of using jQuery Chosen for 2 <select> elements. Each element contains the same values and I'm using loops to put selected values in an array and disable every value which has already been put in that array and is not the selected option. In other words: I always disable the doppleganger.

I'm trying to limit the number of selected value with the last loop, by using a data-attribute "maxpersons" and compare it with the number of selected values.

Unfortunately, this only works when options have not been pre-selected. If they are, someone can still select one more value. Which shouldn't be allowed.

Also, I'd love to put a <p> tag next to the <select> element when the maximum has been reached and remove it automatically when the maximum has not been reached yet.

Any help would be hugely appreciated! This is the JS Fiddle: http://jsfiddle.net/dq97z/28/


Solution

  • you can put the same code which you used in the change() event in the document.ready() event. Like this,

    $(document).ready(function(){
        var selected = [];
        var chosen='.chzn-select';
        $(chosen).parent().parent().find("option")
          .each(function () {
            if (chosen.selected) {
              selected[chosen.value] = this;
            }
          })
          .each(function () {
            this.disabled = selected[this.value] && selected[this.value] !== chosen;
          })
          .each(function () {
            if ($(this).parent().data('maxpersons') === $(this).parent().find('option:selected').length) {
              $(this).parent().find('option:not(:selected)').prop('disabled', true);
            }
          });
        $('.chzn-select').trigger("liszt:updated");
    })

    Thanks for the code snippet...!