Search code examples
javascriptjquerybootstrap-4sortablejs

How can i get data-id value(id) store in Array using JavaScript?


how can i get id number(data-id) using JavaScript. I'm using sortable.min.js for drag & drop. i want to get the td ID(data-id) which is inside of #drop table and store it into a array(sort)?

table.html

   <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Story</th>
            </tr>
        </thead>
        <tbody id="drop" class="sortables">
            <tr>
                <td data-id="67">67</td>
                <td>this is test post for (news2)d</td>
            </tr>
            <tr>
                <td data-id="59">59</td>
                <td>how to use custom fonts in dja</td>
            </tr>
           <tr>
               <td data-id="51">51</td>
               <td>how can i merge two forms fiel</td>
            </tr>
        </tbody>
    </table>

    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Story</th>
            </tr>
        </thead>
        <tbody id="drag" class="sortables">

        </tbody>
    </table>

script.js

   new Sortable(drag, {
        group: '.sortables',
        animation: 150,
    });


    new Sortable(drop, {
        group: '.sortables',
        animation: 150,
        onChange: function (e, tr) {
            sort = [];
            $("#drog").children().each(function () {
                sort.push({ 'id': $(this).data('id') })
            });
            console.log(sort)
        },
    });

Solution

  • As pointed out, you have a Typo in your Selector:

    $("#drog")
    

    Should be:

    $("#drop")
    

    You can also consider the following.

    new Sortable(drag, {
      group: '.sortables',
      animation: 150,
    });
    
    new Sortable(drop, {
      group: '.sortables',
      animation: 150,
      onChange: function (e, tr) {
        var sort = [];
        $("#drop > tbody > tr").each(function (i, row) {
          sort.push({ 'id': $("td:first", row).data('id') });
        });
        console.log(sort);
      },
    });
    

    Your previous code was targeting the children of #drop, which are <TR> elements and do not have the Data attribute.

    The new code targets the 1st <TD> element of each row. This element has the Data attribute.