Sorting data using JQuery and providing feedback on its accuracy by displaying a message indicating whether

I have an ordered list that can be rearranged.

<div id="reImbursement_msg" style="display: none;"></div>
<div>
    <ul class="sortable reImbursementdiv  cur">
        <li id="sort_five">alpha</li>
        <li id="sort_one">beta</li>
        <li id="sort_four">gamma</li>
        <li id="sort_three">thita</li>
        <li id="sort_two">pie</li>
    </ul>
</div>

My aim is to show a message when users reorder the list. I am comparing two arrays to determine if the order is correct, but it always displays "Incorrect Order" even if the arrays match.

var correctOrder = ["sort_one", "sort_two", "sort_three", "sort_four", "sort_five"];
var userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
    return i.id
});

function arraysEqual(arr1, arr2) {
    if (arr1.length !== arr2.length)
        return false;
    for (var i = arr1.length; i--;) {
        if (arr1[i] !== arr2[i])
            return false;
    }

    return true;
}


$(".sortable").sortable({
    update: function(event, ui) {

        if (arraysEqual(correctOrder, userOrder)) {
                showMsg("reImbursement_msg", "Correct Order", "success");

        } else {
            showMsg("reImbursement_msg", "Incorrect Order", "danger");
            console.log($(".sortable.reImbursementdiv li").toArray().map(function(i) {
                return i.id
            }));
        }


        return true;
    }
}).disableSelection();

function showMsg(box, msg, msgStatus) {
    $("#" + box)
            .removeClass()
            .show()
            .addClass("alert alert-" + msgStatus)
            .html(msg);
}

I have provided a codepen demo as requested:

View Codepen Demo

Answer №1

It appears that in the given example, the userOrder variable is not being updated, which means that the order being compared remains static. Take a closer look at the code snippet provided:

$(function() {
  var correctOrder = ["sort_one", "sort_two", "sort_three", "sort_four", "sort_five"];
  var userOrder = [];

  function arraysEqual(arr1, arr2) {
    // Code for comparing two arrays
  }

  function showMsg(box, msg, msgStatus) {
    // Function to display messages
  }

  $(".sortable").sortable({
    update: function(event, ui) {
      // Update userOrder array here
      if (arraysEqual(correctOrder, userOrder)) {
        showMsg("#reImbursement_msg", "Correct Order", "success");
      } else {
        showMsg("#reImbursement_msg", "Incorrect Order", "danger");
        // Log current userOrder array
      }
      return true;
    }
  }).disableSelection();

  // Initial assignment of userOrder array
  userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
    return i.id;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div id="reImbursement_msg" style="display: none;"></div>
<div>
  <ul class="sortable reImbursementdiv cur">
    <!-- List items with ids -->
  </ul>
</div>

It's also important to consider the sequence of operations when updating the arrays.

I hope this explanation clarifies things for you.

Answer №2

After completing the sorting, it appears that I overlooked the most recent order from the user.

$(".sortable").sortable({
  update: function(event, ui) {
  var userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
      return i.id
  });
      if (arraysEqual(correctOrder, userOrder) == true) {
              showMsg("reImbursement_msg", "Correct Order", "success");

      } else {
          showMsg("reImbursement_msg", "Incorrect Order", "danger");
          console.log($(".sortable.reImbursementdiv li").toArray().map(function(i) {
              return i.id
          }));
      }


      return true;
  }
}).disableSelection();

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

The functionality of a button within an AngularJS directive is not functioning as intended

I am trying to use a directive twice on one page. Inside the directive, there is a button that should toggle between showing the two directives when clicked. However, I'm encountering an issue where the values are not changing even though the ng-click ...

Having trouble with parsing JSON data using jQuery?

I am currently working on retrieving a result set using postcodes with jQuery autocomplete. However, the code I have implemented seems to be displaying an empty set of rows. <html lang="en"> <head> <meta charset="utf-8> <title>Ausp ...

Combining multiple layers of PHP arrays within

In contrast to other posts, my query has a unique twist as I do not possess another array to combine. Instead, I aim to merge arrays within a multi-dimensional array to transform it into a single-dimensional structure. Presented below is the existing arra ...

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...

Discovering the scope of rows containing identical sequences of values

Imagine having a spreadsheet with a single column filled with random numbers, for example: 5, 3, 7, 1, 2, 6, 9, 8, 3, 0. This is just a snippet of the actual dataset which is longer. What if you want to identify the range of rows that contain a specific ...

Encountered an error in the React.js app where it cannot read the property 'Tag' of undefined from domhandler

I recently encountered an issue with my react.js project, which utilizes domhandler v4.2.0 through cheerio. Everything was running smoothly for months until one day, I started getting this error during the build process: domelementtype package includes a ...

How to load a text file into a C++ array

I am attempting to input 20 names from a text file into an array of strings and then display each name on the screen. string creatures[20]; ifstream dataFromFile; dataFromFile.open("names.txt"); for (int i=0; i < creatures->size(); i++){ dataFro ...

Improving the touch responsiveness of my website's navigation menu (drop-down style)

I am currently developing a small website that includes a simple drop down menu feature. When using a desktop, hovering over an item triggers the drop down list, which is straightforward. However, on touch screens, this functionality is not working properl ...

Changing 2D mouse positions to XZ world coordinates using ThreeJS

How can I convert mouse screen coordinates to ThreeJS world coordinates on the XZ plane? I came across a code snippet that successfully converts mouse position to XY world coordinates, but I'm not sure how to modify it for XZ coordinates: var vector ...

What encodings does FileReader support?

Are you looking to easily read user-input files as text? If you can count on modern browser usage, then using FileReader is the way to go (and it works exceptionally well). reader.readAsText(myfile, encoding); It's worth noting that encoding defaul ...

Learn how to leverage the jQuery Draggable plugin to easily create draggable elements and initiate dragging using the HTML5 native Drag and Drop

My goal is to create a unique functionality using the HTML5 Drag And Drop API and jQuery. I want to trigger a dragover event, then have a jQuery draggable object follow the mouse until the dragend event occurs. The reason for this is that I am working on ...

The page continues to refresh even after the fetch() method is called and the promise is resolved, despite setting e.preventDefault()

Greetings! I am currently in the process of creating a basic API using ytdl and express. Specifically, the route I am focusing on is responsible for downloading a file. app.post('/audio', (req, res) => { console.log(`Initiating audio down ...

What could be causing the issue with res.clearCookie() not functioning properly post deployment on Vercel?

Initially, the application functions flawlessly on localhost. However, upon deployment to Vercel, an issue arises when users attempt to log out and the cookies are not clearing as intended with res.clearCookie(). Consequently, even after a page refresh, t ...

Retrieve data based on specific group IDs from an array and organize the results using the ORDER BY

I developed a messaging system that assigns a unique ID to each message and categorizes them to keep related threads connected. The categories are stored in an array, and I can display messages using the following MySQL query. $getid = $link->prepare(" ...

Using React hooks to implement drag and drop functionality

As a backend engineer primarily, I've been struggling to implement a simple drag and drop feature for a slider I'm creating in React. Here's the behavior without using debounce: no-debounce And here's the behavior with debounce: with- ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

The press of the Enter key does not trigger the button

I'm facing an issue with a form that has just one field for user input and a button that triggers some jQuery to hide the login form when clicked. However, pressing enter after entering text causes the page to refresh... I'm starting to think th ...

Is there an issue with this npm version number?

I am trying to include the following dependency in the package.json file of my npm package: "redux-saga": "^1.0.0-beta.0 || ^0.16.0"`. When I install this package in a project that already has "redux-saga": "^1.0.0-beta.1 I am expecting npm/yarn to on ...

Acquire an image from Angular API

I'm attempting to fetch a logo image (such as jpeg, png, gif) from an API. While I can see the image in the Network tab, the console is throwing an error, which is displayed in the attached image. Any ideas on how to resolve this? I am using htppclien ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...