How can I get the last selected value in a ListBox using jQuery?

I have a list, and I have to limit its selection to 5 elements. If the 6th item is selected, I want to "undo it."

But I am having trouble finding the last selected item and “undo it”. And the last item selected, it is necessary that $ ("# mySelect option: last") ...

How can I get the selected list item?

Thanks!!!

+3
source share
7 answers

This will be done, although there is a brief “flash” of choice (you may need to show <span>under <select>to say something like the maximum choice reached).

$('#mySelect').click(function(e) {
  if ($('option:selected',this).length > 5) {    
     $(e.target).removeAttr('selected');  
  }
});

, .

EDIT:

, , , , IE ( IE <select>), , IE 6 Firefox 3.5.3, . ,

(function($) {

$.fn.maxLimitSelect = function(max) {

  if (!max || !/^\d+$/.test(max)) return this;

  return this.each(function() {

    $(this).bind("click change keypress",{ max: max },function(event) {

      var options = $('option', this);
      var max = event.data.max;
      var selected = $('option:selected', this);
      var indexes;

      if (selected.length === max) {  
       indexes = $.map(options, function(e, i) { 
                   if(e.selected) return i; 
                 }); 
       $.data(this, "indexes", indexes);
      }
      else if (selected.length > max) {
       indexes = $.data(this, "indexes");
       options
         .removeAttr('selected')
         .each(function() { 
           var $this = $(this);
           if ($.inArray($this.prevAll().length, indexes) !== -1) {  
             $this.attr('selected','selected');
           }
         });   
      } 
    });
  });
}

})(jQuery);

$('#mySelect').maxLimitSelect(5);

, . IE Firefox, , IE 6 Ctrl Space , Shift . .

+5

"" ( , ).

AFAIK, , ( ) : .

//Or as noted by @peirix you can try to get it with :selected.
//Note that this will just clear the last (by rendered order) selection...
//not the "last" option that was selected.

if($("#mySelect option:selected").size() >= 6){
  $("#mySelect option:selected:last").attr('selected', null);
}

UPDATE:

, , !... - , ... , , , ; -)

<script>
  $('#mySelect').bind('change', function(){
    if($("#mySelect option:selected").size() == 5){
      //5 picked, (re)store them...
      var sel = [];
      $("#mySelect option").each(function(i){
        if($(this).attr('selected')){
          sel[i] = true;
        } else {
          sel[i] = false;
        }
      });
      $(this).data('selectedIndexes',sel);
    } else if($("#mySelect option:selected").size() >= 6){
      //too many reset to orig...
      $("#mySelect option").each(function(i){
        if($(this).parent().data('selectedIndexes')[i]){
          $(this).attr('selected', 'selected');
        } else {
          $(this).attr('selected', '');
        }
      });
    }
  });
</script>

HTML:

<select id="mySelect" multiple="multiple" size="12">
  <option value="a">aaaaaaaaaaaa</option>
  <option value="b">bbbbbbbbbbbb</option>
  <option value="c">cccccccccccc</option>
  <option value="d">dddddddddddd</option>
  <option value="e">eeeeeeeeeeee</option>
  <option value="f">ffffffffffff</option>
  <option value="g">gggggggggggg</option>
  <option value="h">hhhhhhhhhhhh</option>
  <option value="i">iiiiiiiiiiii</option>
  <option value="j">jjjjjjjjjjjj</option>
  <option value="k">kkkkkkkkkkkk</option>
  <option value="l">llllllllllll</option>
</select>
+2

, . , script , ( ). 5, "".

$("#mySelect").click(function() {
    var num_selected = $('#mySelect option:selected').length;
    if(num_selected > 5) {
        $(e.target).removeAttr('selected');
    }
});

, , , :

$("#mySelect").click(function(e) {
    var num_selected = $('#mySelect option:selected').length;
    if(num_selected > 5) {
        $(e.target).removeAttr('selected');
        alert('You are limited to 5 options at a time...');
    }
});

, . peirix.

+1

:

$("#mySelect option:checked:last").val(); //or not

:

$("#mySelect option").mousedown(function() {
   if ($("#mySelect :checked").length > 5) {
      return false;
   }
   return true;
});

, . , , - , , .

0

? , , ?

, SELECT , "" .

function checkLimits( list, maximum ) {
    var options = list.options;
    var size = options.length;
    var numSelected = 0;

    for( var i = 0; i < size; ++i ) {
        if( options[ i ].selected ) ++numSelected;
    }
    if( numSelected > maximum ) {
        alert( 'You have selected more than ' + maximum + ' options.\n' +
            'Please deselect ' + ( numSelected - maximum ) + ' option(s) then
            try again.' );
        return false;
    }
    return true;
}

onsubmit event, :

<select ... onsubmit="return checkLimits(this.listName, 2)">

You can execute jQueryify, but this should get you started. Taken from http://bytes.com/topic/javascript/answers/93760-please-help-limit-number-selections-multiple-select-list-box#post316514

0
source

This seems to work on a small test page that I did:

$('#mySelect option:selected:gt(4)').removeAttr('selected')
0
source

$('#mySelect option:selected').length;doesn't seem to work on IE. Works fine in Chrome, though.

0
source

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


All Articles