yanickrochon / jquery.uix.multiselect

Completely rewritten, multiselect widget with a more concise API
http://mind2soft.com/labs/jquery/multiselect/
MIT License
139 stars 62 forks source link

Cannot read property 'listElement' of undefined #103

Open smparsons opened 8 years ago

smparsons commented 8 years ago

I ran into this error when trying to programmatically deselect elements from my multiselect. I was following the documentation, and used this code:

var selected = $('.sponsor-multiselect').find('option:selected');
selected.remove();
$('.sponsor-multiselect').multiselect('refresh');

I figured this might be an issue with my code, so I went to the demo page and tried executing this same code against one of the multiselects on the page, and it still threw the same error. Thanks for the help.

yanickrochon commented 8 years ago

I see the problem; the refresh method does not clear the cache from removed options. I'll try to resolve this as soon as I can.

smparsons commented 8 years ago

So I was sort of pressed for time on my project, so I attempted to make a fix for this. I don't know if this helps, but I was able to make a workaround. I created a 'select' public function that looks like this:

select: function(elements) {
  for (var i = 0; i < elements.length; i++)
  {
    var eData.this.optionCache._elements[$(elements[i]).data('element-index')];
    if (eData != undefined)
    {
      this.optionCache.setSelectedSorted(eData, !eData.selected);
    }
  }
}

And then all I have to do is get the elements I want to select or deselect, and then just call $(multiselect).multiselect('select', elements); But I can't tell exactly how hacky this is (not too familiar with the code for this plugin). It appears to work, and this removes the need to call the refresh function. This code makes use of the "setSelected" functionality that the event that listens to element clicks uses.