0

In my AJAX success function, I've written:

rt = JSON.parse(responseText);
for (i = 0; i < rt.length; i++) {
  $("#inv").append("<tr><td>" + rt[i][0] +
    "</td><td><input type='submit' value='Sync' " +
    "class='syncnow' id='sync"+rt[i][6]+"' /></td></tr>");
}

I've tried jQuery code:

$(".syncnow").on("click", function() {
  alert("Hi");
});

Tried .click(), $(".tdclass").on("click", ".syncnow", function() {}) etc., but to no avail. Can anyone help me with this?

Just a student
  • 10,560
  • 2
  • 41
  • 69
Yajat Singh
  • 43
  • 1
  • 1
  • 8

6 Answers6

2

You can't add an event to a not yet created element. You need to add it to a higher place and catch it when it is bubbling up. Try this:

$("body").on("click", ".syncnow", function() {
  console.log('clicked');
} )

$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
Nagy Nick
  • 745
  • 9
  • 19
1

You can attach event to element when created using jQuery()

$.each(rt, function(i, value) {
  $("<tr>", {
    appendTo: "#inv",
    html: $("<td>", {
            html: value[0],
            append: $("<input>", {
                      type: "submit",
                      value: "Sync",
                      "class": "syncnow",
                      id: value[6],
                      on: {
                            click: function(event) {
                                     console.log("clicked");
                                   }
                          }
                    })
    })
  })
})
guest271314
  • 1
  • 15
  • 104
  • 177
0

Try this one

$(document).on("click", ".syncnow", function() {
  alert('clicked');
} )

$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
Hemal
  • 3,682
  • 1
  • 23
  • 54
0

I've written a jquery function, to append syncbuttons to an invElement

$.fn.appendSyncElements = function(responseText, onComplete) {

    var invElement = $(this);
    var rt = JSON.parse(responseText);

    var base_sync_attrs = [];
    base_sync_attrs.push("type=\"submit\"");
    base_sync_attrs.push("value=\"Sync\"");
    base_sync_attrs.push("class=\"syncnow\"");
    var base_sync_attrs_str = base_sync_attrs.join(' ');

    for(var i = 0; i < rt.length; i++) {

        var crt = rt[i];
        var crt_sync_label = crt[0];
        var crt_sync_attrs = crt[6];

        var sync_attrs = [];
        sync_attrs.push(base_sync_attrs_str);
        sync_attrs.push("id=\"sync_" + String(i) + "\"");
        sync_attrs.push("data-sync_index=\"" + String(i) + "\"");
        sync_attrs.push(crt_sync_attrs);
        var sync_attrs_str = sync_attrs.join(' ');

        var syncElement = $('<input ' + sync_attrs_str + ' />');

        syncElement.click(function(e) {
            var syncBtn = $(this);
            console.log("the syncBtn was clicked at index " + String(syncBtn.data('sync_index'));
            var syncEvent = {
                'event' : e,
                'button' : syncBtn,
                'fullresponse': crt,
            };
            if(typeof(onComplete) === 'function') {
                onComplete(syncEvent)
            };
        });

        var tableRowElement = $('<tr><td class="synclabel" ></td><td class="syncinput" ></td></tr>');
        tableRowElement.find("td.synclabel").html(crt_sync_label);
        tableRowElement.find("td.syncinput").append(syncElement);

        invElement.append(tableRowElement);

    };


};

Usage

$("#inv").appendSyncElements(responseText);

Or

$("#inv").appendSyncElements(responseText, function(syncResult) {
    console.log("This is a custom Complete Method");
});
classicjonesynz
  • 4,012
  • 5
  • 38
  • 78
0

You can use document on click event:

$(document).on("click",".syncnow",function() {
   alert("Working");
});

Also you can check my answer here:

Why is jQuery on-click event handler not working properly for dynamic loaded DOM elements?

Thanks

Community
  • 1
  • 1
Sagar Arora
  • 1,743
  • 1
  • 10
  • 19
-1
$("body").on("click",".syncnow", function() {} )
Yajat Singh
  • 43
  • 1
  • 1
  • 8
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Apr 05 '17 at 07:15
  • I just posted the answer copying from someone who previously commented on the question and then removed the comment. Thats why I didnt post the explanation – Yajat Singh Apr 07 '17 at 07:06