JQuery UI Selectable find the <li> element in the list that the user clicked on

984 Views Asked by At

I want to be able to get the <li> element that the user clicked on in a jQueryUI selectable. This is because I want to find if the element they clicked on is already selected or not, and then do something based off that. Here is the code I have working:

$(document).ready(function() // Execute all of this on load 
  {
    // Add week selector
    $(function() {
      var startElementSelected = false;

      $("#popupWeeks").selectable({
        start: function(e) {
          var classSelected = e.toElement.className.search("ui-selected");

          if (classSelected != -1) {
            startElementSelected = true;
          } else {
            startElementSelected = false;
          }
        }
      });
    });
  });

The issue is that this works fine for chrome, but not for firefox and I could do with it working for both. I looked for the firefox equivalent of e.toElement.className but couldn't find anything, and I'm having trouble with event handling on click events.

Any help is greatly appreciated.

1

There are 1 best solutions below

4
On

One of the main benefits of jQuery is that it takes care of the different browser inconsistencies under the hood for you so you should probably use it in this case as well.

Since jQuery selectable gives the class ui-selected to the selected (clicked) element, what you can do is find the li element within the selectable that has that class. For example:

$('#popupWeeks li.ui-selected');

Or you can check if the element has the needed class like:

element.hasClass('ui-selected');

Here is a fiddle example

EDIT:

Based on you comment, I believe the way you can solve what you need is to keep track of selected elements in some structure.

Then add/remove elements depending on user behavior.

I decided to use an array to achieve this:

 var selectedItems = [];                                   // array to hold currently selected items

 $( 'li.ui-widget-content' ).on('click', function() {

     var id = $(this).attr('id'),
         isSelected = $(this).hasClass('ui-selected');

     if(selectedItems.indexOf(id) != -1) {                 // if element already selected, alert us
         alert('Product #' + id + ' was already clicked');   
     } else if(isSelected) {                               // if element selected for first time
         selectedItems.length = 0;                         // clear the array
         $('.ui-selected').each(function() {
             selectedItems.push($(this).attr('id'));       // add all the selected items
         });
     } else {                                              // otherwise element is unselected and we remove it
         selectedItems.splice(selectedItems.indexOf(id), 1);   
     }
     console.log('selected items: ' + selectedItems);      // open the console to see the selected items after each click
 });

Here is a fiddle example