Search code examples
htmljqueryjquery-ui-sortabledynamically-generated

jQuery UI sortable dynamic target not working


I have two tables in my html. The first is loaded on page load, the second is generated on button click. My sortable function does not apply to the generated table.

Can you explain why?

Here is my Javascript some.js:

// sort all kinds of tables
$(function(){
  $('table').sortable();
});

// generate new table
$(document).on('click','#test',function(){

  let str = "<table>
               <tr>
                 <td>1</td>
                 <td>2</td>
               </tr>
               <tr>
                 <td>3</td>
                 <td>4</td>
               </tr>
             </table>"

  let content = $.parseHTML(str)

  $('#main').html(content);
  
})

And here the actual html file index.html:

<!DOCTYPE html>
<html>
  <head>
    <script defer src="jquery/3.5.1/jquery-3.5.1.min.js"></script>
    <script defer src="jquery/jquery-ui-1.13.1.js"></script>
    <script defer src="some.js"></script>
  </head>
  <body>

    <div id="main">
      <table>
        <tr>
          <td>1</td>
          <td>2</td>
        </tr>
        <tr>
          <td>3</td>
          <td>4</td>
        </tr>
      </table>

      <input type="button" id="test" value="Generate Table" onclick="">
    </div>

  </body>
</html>

Solution

  • The generated table does not exist in the DOM in the ready event when you call $('table').sortable(); The table is added to the DOM later as response to the click event. You should call $('table').sortable(); after you add the table to the dom

    This should work:

    $(document).on('click','#test',function(){
    
      let str = "<table>
                   <tr>
                     <td>1</td>
                     <td>2</td>
                   </tr>
                   <tr>
                     <td>3</td>
                     <td>4</td>
                   </tr>
                 </table>"
    
      let content = $.parseHTML(str)
    
      $('#main').html(content);
      $('#main table').sortable();
    })