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

I am using jQuery Chosen for 2 <select> elements. Each element contains the same values, and I use loops to place the selected values ​​in the array and turn off each value that has already been placed in this array, and is not a selected parameter. In other words: I always turned off doppleganger.

I am trying to limit the number of selected values ​​to the last cycle using the data attribute "maxpersons" and compare it with the number of selected values.

Unfortunately , this only works when the parameters have not been previously selected . If they are, someone else can choose another value. Which should not be allowed.

In addition, I would like to put the <p> next to the <select> element when the maximum is reached, and delete it automatically when the maximum is not yet reached.

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

+4
source share
1 answer

you can put the same code that 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 ...!

+5
source

Source: https://habr.com/ru/post/1396354/


All Articles