'RefernceError: Can't find variable: deleteChap

I am using Jquery to append elements to an element and I have added an onclick to one of the <td> to call a function present in the same file.

Here is the code for the element:

let x = 0;
let element = `
<td class="px-4 py-3 text-sm">
  <button onclick="deleteChap(${x})">
     <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="text-red-600 w-6 h-6" viewBox="0 0 16 16">
        <path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z" />
     </svg>
  </button>
</td>`

$('#holder').append(element)

This is the function

function deleteChap(x) {

  let chapid = chapids[x];

  Swal.fire({
    title: `Are you sure you want to delete the chapter? This action is irreversible.`,
    showCancelButton: true,
    confirmButtonText: 'Yes, delete it!',
  }).then((result) => {
    if (result.isConfirmed) {
      supabase.from('chapters').eq('id', chapid).delete().then(({data, error}) => {

        if (error) {
          erroralert(error.message);
        } else {
          successalert(`Chapter ${chapternum} - ${title} deleted successfully.`);
          window.location = `/dashboard/series/${seriesid}`;
        }

      })
    }
  })

}

I get the following error when I click on one of the buttons: ReferenceError: Can't find variable: deleteChap

The js file is connected to the html file with <script defer src="/js/dnovelinfo.js" type="module"></script>

Can I get some help?



Solution 1:[1]

As per @Bravo and @Always Helping, I tried window.deleteChap = function deleteChap() and it worked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Electric Dragon