I want to use Sortable in the jQuery UI to get information about the elements even after the li elements are sorted.

Asked 2 years ago, Updated 2 years ago, 96 views

I am currently learning programming while creating a Weba application.
We use Sortable in jQuery to sort li elements.
The source code below is the code that drags the elements to sort them arbitrarily and then clicks the elements to output innerHTML to the console.
However, after sorting the elements, click to get information about the different elements.I would appreciate it if you could tell me how to implement it.

The for statement is executed only once the page is opened, so I think there is an error when the order of the elements changes, but I can't find any implementation other than the source code above.

$(function(){
        // Make the list sortable
        $('#sortable').sortable({
          // Update each time you sort by update
          update:function(){
            // Obtain and output the current order in toArray
            $('#log').text($('#sortable').sortable('toArray'));
          },
        });
      });
      window.addEventListener('load', function(){
        let sortable= document.getElementById('sortable');
        let liClass= document.getElementsByClassName('liClass');

        for(leti=0;i<liClass.length;i++){
          liClass[i].addEventListener('click', function(e){
            console.log(`${liClass[i].innerHTML}`);
          });
        }
      });
<!DOCTYPE html>
<html>
  <head>
    <metacharset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Sample Sortable</title>
    <!--- jQuery, loading jQuery UI -->
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <!--Sortable Implementation-->
    <body>
      <!--Add id attribute to list-->
      <ulid="sortable">
        <liclass="liClass" id="1">item 1</li>
        <liclass="liClass" id="2">item 2</li>
        <liclass="liClass" id="3">item 3</li>
        <liclass="liClass" id="4">item 4</li>
        <liclass="liClass" id="5">item 5</li>
      </ul>
      <p> The order of the list is <span id="log"></span>"
    </body>
     </head>
</html>

javascript html jquery jquery-ui

2022-09-30 19:35

1 Answers

It has been resolved as follows.

$(function(){
     // sortable configuration
      $('#sortable').sortable({
        update:function(){
          $('#log').text($(this).sortable('toArray'));
        },
      });
      // Click handler settings for list items
      $('.liClass').on('click', function(){
        console.log($(this).html());
      });
    });
 


2022-09-30 19:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.