user0129e021939232
user0129e021939232

Reputation: 6355

jquery sortable validation

I'm using jQuery validation in order to sort banners on a website.

I have three types of banners:

The banners carousel has a few rules no more than 7 banners are allowed into the carousel and four of these can be custom, with the four of these being selectablebanners. I've got the logic for this as follows:

 // no more than 7 banners allowed 
   $("#sortable1").sortable({
    connectWith: '.connectedSortable',
    //receive: This event is triggered when a connected sortable list has received an item from another list.
    receive: function(event, ui) {
        // so if > 7
        if ($(this).children().length > 7) {
            //ui.sender: will cancel the change. Useful in the 'receive' callback.
            $(ui.sender).sortable('cancel');
            alert('Your selection has been cancelled. A maximum 7 banners are allowed in the carousel.');
        }
        if ( $('#sortable1 .selectablebanner').length > 4) {
            alert('Your selection has been cancelled. A maximum 4 custom banners are allowed in the carousel.');
            $(ui.sender).sortable('cancel');
        }  
    }
}).disableSelection();
});

Another rule I have in place is that a default banner cannot be removed but it can be sorted. I've implemented this as so:

$("#sortable2").sortable({
cancel: ".ui-state-disabled",
  receive: function (event, ui) {
       if (ui.item.hasClass("defaultbanner")) {
           $(ui.sender).sortable('cancel');
           alert("This is a default banner, it can be sorted but not removed.");
       }
   }

});

However I would like to amend this slightly but have no idea how to begin with this logic as it is slightly more advanced.

The rule I want to implement is that if there are 2 or more "selectedbanners" in ul#sortable1 then the default banners can be removed. However if only for example there is a single defaultbanner and a single selectablebanner. Then I would like my previous validation to apply which is that a default banner cannot be removed.

Can someone please help me to solve this problem.

I've created a jsFiddle which has my full code.

Thanks in advance.

Upvotes: 1

Views: 921

Answers (1)

Trevor
Trevor

Reputation: 16116

It's not completely clear to me, however this is my best guess as to what you might be looking for.

$("#sortable2").sortable({
    cancel: ".ui-state-disabled",
      receive: function (event, ui) {
           if (ui.item.hasClass("defaultbanner") && $('#sortable1 li').length <= 1) {
               $(ui.sender).sortable('cancel');
               alert("This is a default banner, it can be sorted but not removed.");
           }
           else if($('#sortable1 li').length <= 1) {
              $(ui.sender).sortable('cancel');
              alert('You must have at least two banners');    
          }
       }
  });

Fiddle

Upvotes: 1

Related Questions