I'm aware similar questions have been asked and answered but I can't seem to get them to apply to my issue.
Below is the code that sends an ajax post when the form is submitted
$form.on("submit", function(event) {
event.preventDefault();
$.ajax({
url: url,
data: JSON.stringify({ description: desc }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function(data) {
$(".list").append(
'<li><input type="checkbox" value="' +
data.id +
'">description</li>"
);
createOnClicks(data.id);
},
error: function(error) {
//list errors },
complete: function() {
//reset form
}
});
});
this is part of the createOnClicks()
function:
function createOnClicks(id) {
var listId = "#" + id;
$(listId).on("click", function(event) {
var value = $(this).is(":checked");
if (value) {
console.log("checked");
$.ajax({
url: "/listapi/" + id + "/complete",
type: "POST",
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log(data);
$(listId)
.parent("li")
.addClass("complete");
}
});
} else { ...
}
});
createOnClicks
works correctly when it is called on elements that are there when the page loads, but won't work on elements that are added with the ajax post.
$(listId)
returns an empty object when called within createOnClicks()
, despite on the line above `console.log(listID) shows the appropriate value.