Is there a way to determine the quantity of items within a sortable div?

In my HTML document, there are multiple divs containing smaller divs that can be rearranged within each other. Upon loading the document, a random assortment of these smaller divs are added to #boxtop.

Below is a snippet of my HTML code:

<html>
<body>
<head>
    <title></title>
    <script link src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <link rel = "stylesheet" type="text/css" href = "style.css">
    <script src="jquery-ui.min.js"></script>
    <div id = "boxtop" class = "dragInto"></div>
    <button type="button" id="button">My Children!!!</button>
    <div id = "eqbox"></div>
    <div id = "box1" class = "ansBox"></div>
    <div id = "box2" class = "ansBox"></div>
    <div id = "box3" class = "ansBox"></div>
</head>
</body>
</html>

Here is the relevant jQuery code:

$(document).ready(function()
{
    $("#boxtop").sortable
    ({
        connectWith: ".ansBox"          
    });

    $(".ansBox").sortable
    ({
        connectWith: ".ansBox"          
    });

});

$(document).ready(function()
{
    $("dragInto").droppable
    ({
        accept: ".box"
    });
});

var numChild = $("#boxtop").length;
$(document).ready(function()
{
    $("#button").click(function() 
    {
        console.log(numChild);
    });
});

My query is this: How can I retrieve the number of elements present in a sorted div? Currently, when trying to display this value using numChild, it only shows "1". Additionally, if I were to drag numerous elements from #boxtop to .box1, how would I determine the total count of elements inside .box1?

Answer №1

The property known as .length provides information regarding the number of elements associated with the jQuery object on which it is utilized. In the case where $("#boxtop") matches one element, the value of $("#boxtop").length will be 1.

To determine the total number of elements contained within #boxtop, it is necessary to select all descendants and subsequently verify the length using .length:

// All descendants:
$("#boxtop").find("*").length    // or:
$("#boxtop *").length

// Or calculate immediate children only:
$("#boxtop").children().length

In your scenario, determining the immediate children count is likely what you require. However, refrain from establishing a global variable such as:

var numChildren = $("#boxtop").children().length;

...as this action sets numChildren to the length at the beginning of page loading, before any user interaction has occurred. Instead, ensure to assess $("#boxtop").children().length or $(".box1").children().length precisely when the value is needed.

Additionally, there is no necessity for three distinct $(document).ready(...) handlers: consolidate all of your code within a single ready handler, or if your <script> tag is located at the bottom of the body, a ready handler may not be required at all.

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

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

Activate or deactivate a text box within a table based on the checkbox's status

I am seeking assistance with jQuery to enable or disable a textbox within a table when a checkbox is checked. Below is the code snippet from my edit.cshtml file. <table id="scDetails" class="dataTable"> <thead> & ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...

Changing the order of rows and columns with CSS3 and DOM manipulation

I have implemented the following CSS code to alternate the background color of li elements. However, I am facing an issue where I need the CSS styling to remain consistent even if the rows have the .hidden class applied to them (with .hidden class having d ...

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

Ways to categorize specific columns based on certain criteria

In the code snippet below, I am working with a data grid in premium version. There is a boolean field that determines whether to display the data grouped or inline. If the boolean is true, I want to show the expand group, otherwise display it inline withou ...

Can the dropbox option be automatically updated when input is entered in another text field?

I'm working on a form with a dropdown containing category names and a text field for entering the category code. What I need is for selecting a category name from the dropdown to automatically display the corresponding category code in the text field, ...

Fixing Sticky Navigation Bar on Scroll (JavaScript, HTML, CSS)

I'm working on this site as a fun side project, but I've hit a roadblock. The sticky nav bar I implemented jumps when the user scrolls down far enough. Despite reading through other discussions, I can't seem to figure out the solution. I su ...

I'm facing an issue with this error message - DiscordAPIError: Unable to send a message that is empty. How can I

What's the solution to this issue? Error: UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message Code: let y = process.openStdin() y.addListener('data', res => { let x = res.toString().trim().split(/ +/g) ...

Troubleshooting an issue with my JQuery code in Internet Explorer that does not occur in

Hi everyone, I'm having some trouble with the code below. It seems to be working fine in Firefox and other browsers, but not in IE. I've been checking for syntax errors but can't seem to find any. Any advice would be greatly appreciated! $( ...

Tips for creating a scrollable smiley input field

I have a chat system where I am incorporating smileys from a predefined list. QUERY I am looking to create a scrolling feature for the smileys similar to how it is implemented on this particular website. The twist I want to add is to have this functiona ...

Create static HTML web pages using information from a text file

Exploring a new concept of a random joke generator that loads a unique html page with a quirky joke every time. Currently, the main index page is structured like this: <!DOCTYPE html> <html> <head><title>Jokes</title> ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

Alter the default time zone in JavaScript

PHP features a function known as date_default_timezone_set which impacts the GMT time that is used by the Date() command. Is there a way for this function to also impact JavaScript? Here is a custom function I have: function calcTime(offset) { d = n ...

Subscriber client successfully activated and operational via the command line interface

I have incorporated a script into my PHP file that reads the Pusher channel and performs various actions when a new event occurs on the specified channel. If I access the following URL in my browser: http:/localhost/pusher.php and keep it open, the p ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

How to access a variable from within a Phonegap DB function and return it outside of the

I'm struggling with a phonegap db JavaScript script that isn't returning the final string variable "feeds" outside the function. It's currently showing as "undefined". I need help making the necessary changes to properly return the "feeds" v ...

Print Vue page with the same styling as the original

How can I add a print button to my application that prints the page with the original CSS styles? I am currently using window.print() function and have a separate file called print.scss with specific print styles. @media print { header {display:none; ...