Search code examples
javascriptnode.jsfunctionwebsweetalert2

How to use function in another public js file


I originally had the following code commands for simplicity I put it just below the body in the html file. This is my code:

<script>
async function ThemMonHoc() {
    MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
    MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
async function MyPopUpPost(title,route) {
    var a = await Swal.fire({
        title: title,
        html: '<input id="Result" class="swal2-input" type="text"></input>',
        showDenyButton: true,
    })
    var value = $('#Result').val()
    if (a.isConfirmed) $.post(route,{a:value})
}
</script>

It seems that the function MyPopUpPost will be reused many times in other html files and leaving the code here will not be very neat. So, I put it in another file.

This is my code in UtilitiesForm.js:

        export async function MyPopUpPost(title, route) {
        var a = await Swal.fire({
            title: title,
            html: '<input id="Result" class="swal2-input" type="text"></input>',
            showDenyButton: true,
        })
        var value = $('#Result').val()
        if (a.isConfirmed) $.post(route, {
            a: value
        })
    }

And back to the html file I try import or require to use that function but it is not working:

      <script>
        import {MyPopUpPost} from '/js/UtilitiesForm.js'
        async function ThemMonHoc() {
            MyPopUpPost('Thêm môn học','/ThemMonHoc')
        }
        async function SuaTen() {
            MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
        }
    </script>

Is there a way to redo the work between public JS files?


Solution

  • You have two options,

    1. You can import your file into the HTML by using the script's src attribute.

    Check this out: https://www.w3schools.com/tags/att_script_src.asp

    Then, Change your script to the following and you should be ok:

    <script src='/js/UtilitiesForm.js'></script>
    <script>
        async function ThemMonHoc() {
            MyPopUpPost('Thêm môn học','/ThemMonHoc')
        }
        async function SuaTen() {
            MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
        }
    </script>
    
    1. add type="module" to your script. Check this out: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type