Preventing a draggable item from being dropped into a sortable container when the maximum count has been reached

Check out the following code snippet:

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<style>
#sortable1, #sortable2, #sortable3 {
    border: 1px solid #eee;
    width: 142px;
    min-height: 20px;
    list-style-type: none;
    margin: 0;
    padding: 5px 0 0 0;
    float: left;
    margin-right: 10px;
}
#sortable1 li, #sortable2 li, #sortable3 li {
    margin: 0 5px 5px 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}
</style>
<script>
//    debugger;
var sortableIn = 0;
$(function() {
    $(".draggable").draggable({
        connectToSortable: ".sortable",
        helper: "clone",
        revert: "invalid"
    });
    $(".sortable").sortable({
        revert: true,
        receive: function(event, ui) {
            var $this = $(this);
            if ($this.children('li').length > 2) {
                alert("stopping");
               $(ui.sender).sortable('cancel');
            }
        }
    });
    $("ul, li").disableSelection();
});
</script>
<body>
<ul id="sortable1">
    <li class="ui-state-default sortable">Item 1</li>
    <li class="ui-state-default sortable">Item 2</li>
    <li class="ui-state-default sortable">Item 3</li>
    <li class="ui-state-default sortable">Item 4</li>
    <li class="ui-state-default sortable">Item 5</li>
</ul>
<ul id="sortable3">
    <li class="ui-state-highlight draggable">Item 3</li>
</ul>
</body>

Here's the jsfiddle demo.

I am facing an issue where I need to restrict the number of items that can be dropped into a sortable container to 2. Is there a way to achieve this?

Additionally, I would like to know how I can remove an item from the sortable container when dragging it out. Any suggestions on how to accomplish this task?

Your help is much appreciated!

Answer №1

It's best to opt for $this.sortable('disable'); over $(ui.sender).sortable('cancel'); in this scenario.

Answer №2

I have come up with my own solution.

Check out the demo in the link below:

Solution Demo

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<style>
#sortable1, #sortable2, #sortable3 {
    border: 1px solid #eee;
    width: 142px;
    min-height: 20px;
    list-style-type: none;
    margin: 0;
    padding: 5px 0 0 0;
    float: left;
    margin-right: 10px;
}
#sortable1 li, #sortable2 li, #sortable3 li {
    margin: 0 5px 5px 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}
</style>
<script>
debugger;
var sortableIn = 0;
$(document).ready(function() {

    var removeIntent = false;

    $(".draggable").draggable({
        connectToSortable: ".sortable",
        helper: "clone",
        revert: "invalid",
        revertDuration: 20
    });
    $(".sortable").sortable({
        revert: true,
        revertDuration: 20,
        receive: function(event, ui) {
            var $this = $(this);
            if ($this.children('li').length > 2) {
                $(this).children('li').filter(function() {
                    return $(this).text() == ui.item.text();
                }).first().remove();
            }
        },
        over: function() {
            removeIntent = false;
        },
        out: function() {
            removeIntent = true;
        },
        beforeStop: function(event, ui) {
            if (removeIntent == true) {
                ui.item.remove();
            }
            ui.item.addClass(" dropped ");
        }
    });
    $("ul, li").disableSelection();
});
</script>
<body>
<ul id="sortable1">
    <li class="ui-state-default sortable">Item 1</li>
    <li class="ui-state-default sortable">Item 2</li>
    <li class="ui-state-default sortable">Item 3</li>
    <li class="ui-state-default sortable">Item 4</li>
    <li class="ui-state-default sortable">Item 5</li>
</ul>
<ul id="sortable3">
    <li class="ui-state-highlight draggable">Dog</li>
    <li class="ui-state-highlight draggable">Cat</li>
    <li class="ui-state-highlight draggable">Bear</li>
    <li class="ui-state-highlight draggable">Lion</li>
</ul>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

Despite working smoothly with an HTML form tag, the "req.file" multer is undefined when it comes to HTTP requests from a script

I have created a basic file uploader using multer in Node.js, which works well when uploading files using an html form like this: <form id="uploadForm" enctype="multipart/form-data" method="post"> <input type="file" name="userFile" /> ...

What is the best way to expand the Bootstrap container's width to the maximum size?

I'm having an issue with implementing a DataTable within a Bootstrap container. When viewing the website at maximum width, the table container adds a scrollbar and cuts off the last column in the table. Attempted solutions such as using a `container- ...

What methods can I use to extract a filename from a URL?

I'm currently struggling to extract just the filename from a URL in an attempt to make an AJAX call. Unfortunately, I can't seem to get the text formatting right. While it seems like it should be a simple task, I must be missing something importa ...

Alignment of Inline SVG in HTML

I am struggling to align an inline SVG within a bounding DIV correctly, as shown in this example. <!DOCTYPE html> <html> <body> <div style="border: 1px solid black; height: 50px; width: 100px; vertical-align:top;"> < ...

Dnd-kit: item loses its place in line when dragged over Droppable area

I've encountered an issue while using @dnd-kit. The sorting function works smoothly (e.g. when I drag the 1st element, it sorts correctly), but once I reach a droppable element (green Thrash), the sorting breaks and the 1st element snaps back. You ca ...

What is the best way to smoothly hide and reveal a flex child element?

I am looking to create a flex container where the child element can smoothly animate to shrink and grow, while the remaining child elements expand to fill in the space. The method I have found involves setting the max-width to 0px and the borders' wi ...

Understanding Vue.js: Effectively communicating updates between parent and child components using scoped slots

My goal is to develop a component with two slots, where the second slot repeats based on the number of items in the first slot. I have successfully implemented this using scoped slots. However, I noticed that when the data in the first slot is updated, the ...

What is the best way to modify just a portion of the state in React?

Consider the following State object: const initialState = { data: { user: '', token: '', } } In the Reducer function: case 'DO_SOMETHING': return {...state, data: action.payload } If I make a shallow copy of th ...

Designing geometric forms using the vertices of a Sphere in ThreeJs

My current project involves creating shapes based on vertices that have already been generated using a formula. I have successfully connected lines between these vertices using a threejs method, but now I want to take it a step further and create map tiles ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...

Encountering problem when attempting to incorporate fade in/fade out effect animation

I have a webpage that features multiple buttons, each triggering a fade-in/fade-out animation when clicked. This animation also involves changing the contents of a specific div. Though everything is functioning properly, there is a brief moment (about hal ...

Developing a progress bar with jQuery and Cascading Style Sheets (

Below is the code I'm currently using: <progress id="amount" value="0" max="100"></progress> Here is the JavaScript snippet I have implemented: <script> for (var i = 0; i < 240; i++) { setTimeout(function () { // this repre ...

Attempting to retrieve data from local server 3000 to local server 3001 resulted in an unexpected termination of the input stream

After attempting to make a GET request to the Serp API directly from a React application, I discovered that it was not possible. To work around this issue, I created a local server and implemented the necessary logic. After testing the server using Postman ...

Is relying on jQuery to submit a form without the use of PHP secure?

My website has a user account creation form with a "submit" button that is actually an html type='button', not a true submit button. When this button is clicked, I rely on jQuery to call ('#form').submit(); in order to submit the form. ...

Issues with jQuery Functions Arising After Utilizing .load() to Update div Element Text

After processing form data, I am reloading the content of "#some-div" using the ".load()" function. It successfully refreshes "#some-div" with the updated content. However, the issue I am facing is that none of my other jQuery functions (such as ".some-t ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

How to create a drop-down menu with jQuery hover and mouseout functionality

Looking for assistance with a simple sub-navigation drop-down menu I'm trying to create. The issue is that when the user hovers over a trigger, the #sub-nav fades in with a drop-down menu, but it fades out and back in again when the mouse moves over n ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...