aBloomer aBloomer - 5 months ago 23
HTML Question

How to add o'clock event the append html code using jQuery?

Below is my code trying to add some html to page...

'<div class="uploadClick" style="float:left; margin-right: 10px; margin-bottom: 10px">' +
'<i class="fa fa-times fa-remove"></i>' +
'<i class="fa fa-plus-circle fa-2x" onclick="$("#DocUpload").click()"></i>' +

I can get correct div style on my page when using this jQuery code.

However, the onclick event is not working.

How to add onclick event when append html code using jQuery?


Look at your quotes. You have


Where does that attribute end? Answer: Here:

// --------------^

because that's the first " after the opening ".

You can fix it in at least two ways: By using a ' and escaping it (since this is all in a string delimited by '):

// --------------^^----------^^

or since the text in onxyz handlers is HTML (although people tend to forget that), you could use the named character entity &quot;:

// --------------^^^^^^----------^^^^^^

But better still would be to use modern event handling:

  1. Ditch the onclick attribute entirely

  2. Add a semantic class to that i element, such as trigger-upload

  3. Use delegated handling:

    $(document).on("click", "#DocUploadDiv .trigger-upload", function() {

Even better than that would be to have both elements call the same function, rather than doing a synthetic click:

function handleUpload() {
    // Do whatever you're doing in the #DocUpload click handler now
$(document).on("click", "#DocUploadDiv .trigger-upload", handleUpload);

Or even:

$(document).on("click", "#DocUploadDiv .trigger-upload, #DocUpload", function() {
    // Do whatever you're doing in the #DocUpload click handler now