0

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>
1
  • 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. Commented Jun 16, 2022 at 7:17

1 Answer 1

2

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();
})
Sign up to request clarification or add additional context in comments.

1 Comment

Why does this work? Please add a brief explanation in your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.