javascripthtmlstringonclick

javascript, why you can't add onClick in HTML string, before you add this HTML string to DOM?


I need something like that:

function myfunc(){
   const checkbocClick = () => {
     console.log("chceckbox click")
   }

   createElement = () => {
     let isChecked = (Number(addressPoiData.notSendInfoToDriver) === Number(0))? 'checked': ""
     return `<input type="checkbox" class="form-check-input" id="sent-to-driver" onClick='checkbocClick()' ${isChecked}>`
    }
    return createElement()
}

This function is imported and used in one class, where the append is. But I would like to add a method at this stage to make the code more readable and clear. I don't want to use vanilla javascript because it will cause the mish you have in my code. Is there any way to do this? I've read that it's not recommended, but it doesn't work for me at all. In this version I have an error that

Uncaught ReferenceError: checkboxClick is not defined at HTMLInputElement.onclick

I also tried adding the checkbocClick and createElements functions as regular (not arrow) functions, changing their order, or using ${checkbocClick} in onClick. Nothing helped. I either received the error above or no response after clicking.


Solution

  • It seems, checkbocClick is visible only inside myfunc() function. On the other hand, when you add onclick on input, you need function that is visible on the document level.

    Instead, you can move the function checkbocClick outside other functions to make it visible for input.

    
    function myfunc(){
       window.checkbocClick = () => {
         console.log("chceckbox click")
       }
       createElement = () => {
           let isChecked = (Number(addressPoiData.notSendInfoToDriver) === Number(0))? 'checked': ""
           return `<input type="checkbox" class="form-check-input" id="sent-to-driver" onClick='checkbocClick()' ${isChecked}>`
        }
        return createElement()
    }