My button is firing twice. Other SO posts say to unbind the click function from the document. The problem is that the HTML elements are being dynamically appended to the document, so i need to call:
$(document).on("click", "#id", function())
But how to I "unbind" the click function from a document.on statement?
Here's my full code:
//Add Column
$(document).on("click", ".btn-add-tbl-col", addColumn);
function addColumn() {
console.log("addColumn fired!"); //Console shows this statement twice when I click the button once
//Identify the table into cache
var $tbl = $("#main-tbl-sch-tbl");
//Count the number of records
var rows = $tbl.find("tr.record").length;
var columns = $tbl.find("th.tbl-column").length;
columns++;
var newCol = "<th class='tbl-column' data-id='0'>*Click*</th>";
$(newCol).insertBefore($tbl.find("th.no-click-last"));
$tbl.children("tbody.tbody-records").children("tr").each(function () {
var $td = '<td class="record-cell" data-id="0" data-isstatic="1" data-col="' + columns + '" data-row="' + rows + '" data-colID="0" data-rowID="0" data-asid="0" data-deid="0" data-isnull="1" data-nameid="0" data-tbllookupid="0" data-collookupid="0" data-munterspn="0">*Click*</td>';
$(this).append($td);
});
var newTableWidth = parseFloat((167 * columns) + 33 + 33);
$tbl.css("width", newTableWidth.toString() + "px");
}
FYI: There is no other click function binded to the class
You can unbind the event the same way you binded it, but with off() method.
So per documentation you need:
$(document).off('click', '#id').on("click", "#id", function())
In your exact problem you need:
$(document).off("click", ".btn-add-tbl-col").on("click", ".btn-add-tbl-col", addColumn);