Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading