Check if the data-indices of several div elements are in sequential order using a jQuery function

Is there a way to implement a function in jQuery-ui that checks the order of div elements with data-index when a submit button is pressed? I have set up a sortable feature using jQuery-ui, allowing users to rearrange the order of the divs.

Here is an example of the DOM structure:

<div class="sequence_boxes sortable sortable_area ui-sortable">
  <div class="box" data-index="0">..</div>
  <div class="box" data-index="1">..</div>
  <div class="box" data-index="2">..</div>
  <div class="box" data-index="3">..</div>
</div>

Below is the jQuery code snippet:

$('.sequencing').append('<div class="sequence_boxes sortable sortable_area"></div>');

$('.sequence_option').each(function (i) {
    $('<div class="box"></div>').appendTo($('.sequence_boxes')).append(this);
    $(this).attr("data-index", i);
    $(this).parent().attr('data-index', i);

});

$('.sequence_boxes').each(function () {

    // get current div
    var $div_parent = $(this);

    // get array of childs in parent div
    var $divsArr = $div_parent.children('.box');

    // sort array of childs in parent div (#sponsors) randomly
    $divsArr.sort(function (a, b) {

        // Get a random number between 0 and 10
        var temp = parseInt(Math.random() * 10);

        // Get 1 or 0, whether temp is odd or even
        var isOddOrEven = temp % 2;

        // Get +1 or -1, whether temp greater or smaller than 5
        var isPosOrNeg = temp > 5 ? 1 : -1;

        // Return -1, 0, or +1
        return (isOddOrEven * isPosOrNeg);
    })

    // append child items to parent
    .appendTo($div_parent);
});



$('.sortable_area').sortable({
    dropOnEmpty: true,
    forcePlaceholderSize: true,
    forceHelperSize: false,
    connectWith: ".sequence_boxes",
    scrollSensitivity: 200,
    scrollSpeed: 40,
    placeholder: "ui-sortable-placeholder",
    cursor: "move",
    distance: 0.5,
    delay: 100,
    opacity: 0.6,
    tolerance: "pointer",


}).disableSelection();

Answer №1

Here is a straightforward solution:

DEMO

  var correct_pos = 0;
  $('.square').each(function(){
    var current_pos = $(this).data('position');
    if(current_pos !== correct_pos) {
      alert('Not in proper order');
      return false;
    } 
    correct_pos++;
  });

UPDATE:

Click here for a more consistent approach:

Your scenario:

$('.group_of_squares .square').checkOrder('asc', 'position');

Instructions:

$(selector).checkOrder(order, data, [error], [good]);

Further details:

  • order: 'asc' or 'desc' (sorted by).
  • data: 'position' ... any data value.
  • error [optional]: custom function when a node is out of sequence (the problematic node is passed as an argument).
  • good [optional]: custom function to execute when everything is correctly ordered.

Origin:

jQuery.fn.extend({
  checkOrder: function(orderedBy, dataIndex, successFunc, errorFunc){
    var correct_position = 0, incr = 1, error = false, ele = this;
    if(orderedBy == 'desc') {
      correct_position = this.length - 1;
      incr = -1;        
    }
    this.each(function(){
      var curr_position = $(this).data(dataIndex);
      if(curr_position !== correct_position) {
        if(errorFunc) errorFunc.call(ele, this);
        error = true;
        return false;
      } 
    correct_position += incr;
    }); 
    if(!error && successFunc) successFunc.call(this, this);
    return this;
  }
});

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

Creating a basic JSON array using the push method

When adding comments to a blog post using the line: blogpost.comments.push({ username: "fred", comment: "Great"}); The JSON structure of the comments section will look like this: "comments":[{"0":{"username":"jim","comment":"Good",},"1":{"username":"fre ...

What could be causing the issue of CSS animation not functioning properly when used in conjunction with a

I am working on creating a switch button with CSS and JavaScript that needs an animation when toggling or clicked. The only issue I am facing is related to the animation. I am wondering if there might be any problem with the positioning (relative, absol ...

Is there a way to store image URLs in a fashionable manner?

Hey there! I've been working on creating a HTML page that showcases multiple images. Everything is running smoothly on my localhost, but when I try to access it online, the images take forever to load. Any suggestions on how I can cache image URLs in ...

JavaScript's async function has the capability to halt execution on its own accord

Presented here is a JavaScript async function designed to populate a sudoku board with numbers, essentially solving the puzzle. To enhance the user experience and showcase the recursion and backtracking algorithm in action, a sleeper function is utilized b ...

I am looking to showcase a text directly from the properties file using the thymeleaf template engine

I have two files named message_ar.properties and messages_fr.properties for internationalization purposes. Within my HTML file, I am attempting to show the correct label for a confirm message. To accomplish this, I am utilizing Thymeleaf as my template e ...

Tips for creating an HTML report using Python

Currently, I am searching for a solution to convert my saved matplotlib graphs as png files along with some data frames into HTML format. This is similar to how I typically use R2HTML in R. Despite my efforts, I have not been able to locate clear informat ...

Having trouble getting the img file to show up in the img tag - the src URL is not updating

<div class="col-lg-3 col-md-4 pl-md-1"> <label class="ORGAd16-preview"> input type='file' name="modelvariant_file" id="imageUpload" accept=".png, .jpg, .jpeg" > <img id="ima ...

Intersecting table columns with a different data table

My task is to create a table with a column that contains another table, where I want the colors of each alternating row to be different. Please refer to the image below (ignore the "CharacterAgain" column). Below is an example of AngularJS code for the ta ...

Tips for achieving a seamless background texture alignment around a sphere with Three.js

https://i.sstatic.net/9SyRc.jpg I'm facing an issue with setting a texture on a large sphere in my code. Despite trying different wrapping options, the background still appears not to be smooth due to a visible seam where the two parts of the texture ...

css malfunctioning user interface

I'm struggling to figure out how to design a CSS toolbar. My goal is to create a 22x22 button toolbar with 4 buttons. I have this PNG image: and the following code: <style> #nav {background: url(content/images/crtoolbar.png) no-repeat;height: ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

Determine the SVG arc connecting two given points

My situation involves having coordinates for points X and A, A',... as follows: X [x,y] (starting point) A [a,b], A'[a',b'], etc. (ending points) I also have information about angles XCA, XCA', etc. However, I am struggling t ...

Conceal and reveal elements using a specific identifier with

Web Development Guide <ul id="menüü"> <li id="meist"> <p><a href="meist.html">Meist</a></p> </li> </ul> <div id="submenu"> <ul id="submeist"> ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

Getting data from a response in Express.js involves using the built-in methods provided by

I am a beginner at Node.js and I'm currently experimenting with client-server communication. Below are the codes I've been working on: server: app.post('/zsa', (req, res) => { res.send("zsamo"); }); client: fetch(&qu ...

How to Use Jquery to Deactivate a Div with a Background Color

Currently, I have a div that contains several child divs. My goal is to disable the parent div and all of its children, showing them in gray color. I initially tried using the CSS property opacity, but unfortunately, the background color didn't change ...

Add JavaScript code to your project without bundling it as a module

Is it possible to incorporate a JavaScript library into webpack that is not structured as a UMD-compatible module (AMD, CommonJS)? I want the library to be included in a <script> tag only when necessary and managed by webpack without passing through ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Track and display the number of times a button is clicked using

I'm looking to create a button click counter that changes the text on the button when clicked. I want to write this information to a database as well, but I'm struggling with the implementation. <button type="button" class="btn btn-info" styl ...

Encountering issues while establishing a connection to SQL Server through Node.js

I've developed a Node.js application to interact with SQL Server. Here's the code snippet: app.get('/SalesStatistics', function (req, res) { var Connection = require('tedious').Connection; // configuration for the databas ...