Wednesday 26 October 2016

Cleaner approach to bind an event to dynamic generated element in Jquery

Instead of binding an event in a single line  using Traditional approach which actually difficult to parse quotes , commas and values :
"<td><a href='#'><span id='showHidelinkText"+ id + "' onclick='openJsonData(\"" + id+ "\");return false;'>Show JSON</span></a></td>"



We can use the following approach which appends the child elements to the parent and then append into DOM. After appending the new element into DOM, we can bind on() method on element selector.
Event handlers attached using the on() method will work for both current and FUTURE elements.
This way we can overcome the difficulty for adding or removal of the  parameters & attributes in the dynamic generated section.



var formId = "batchclosurestatusForm";
    var action = "forceCloseStatus";

    if (txnJson != null) {
        var txnObj = $.parseJSON(txnJson);
       
       
            var actionTDElement = $("<td></td>");
            var spanElement = $("<span id="+txnObj._id+" class='iconSpan' > </span>");
           
            var iconElement =  $(document.createElement("a"))
                            .attr({ href: '#'})
                            .addClass("forceClosureAction")
                            .append($("<i class='fa fa-toggle-on' aria-hidden='true'></i>"));
                          
           
            spanElement.append(iconElement);
            actionTDElement.append(spanElement);
       
        rowCount++;
        var newTableRow =
            "<tr id='" + txnObj._id+ "DataRow' class='dataRow'>"
           
                +"<td>"    + txnObj._id + "</td>"
                +"<td>" + txnObj.device_code +"</td>"
                +"<td>" + txnObj.force_closure_by + "</td>"
                +"<td>" + actionTDElement.html() + "</td>"
                   
            +"</tr>";

   
        $('#batchClosureLogTable').append(newTableRow);
        $("#"+txnObj._id).on('click',function(){
            // Do something
           
            alert("hello");
           
        });

No comments:

Post a Comment