I created several buttons dynamically. I added click handlers to them using $.on function in jquery. Sometimes the click is working and sometimes it doesn't register the click. I have to refresh again the page to check the click is working or not. Why is this happening?
function searchCompany() {
$("#search-result").html('');
let name = $("#company-name").val();
$.ajax({
url: `http://localhost:5000/manualharmonization/query?name=${name}`,
success: function (data) {
data.map((el, i) => {
$("#search-result")
.append(`<tr class="list-item"><td>${el.applicant_original}</td>
<td><button class=${el.flag == 0 ? "button" : "submitted"} id="${i}"
type="button">Select</button></td>
</tr>`);
res.push({
applicant_original: `${el.applicant_original}`,
flag: `${el.flag}`, name_friendly: `${el.name_friendly}`, appl_ref_no: `${el.appl_ref_no}`,
psn_id: `${el.psn_id}`, appl_key: `${el.appl_key}`
})
});
},
error: function (e) {
console.log(e);
alert(JSON.stringify(e));
}
});
$("#search-result").on("click", "button", function () {
if (res[`${event.srcElement.id}`].flag == 0) {
$(`#${event.srcElement.id}`).removeClass("button");
$(`#${event.srcElement.id}`).addClass("submitted");
res[`${event.srcElement.id}`].flag = 1;
} else {
$(`#${event.srcElement.id}`).removeClass("submitted");
$(`#${event.srcElement.id}`).addClass("button");
res[`${event.srcElement.id}`].flag = 0;
}
})
}
Try this and i am sure this will definitely work for you.