I'm creating a menu and submenu items all async.
It seems like everytime I create a button Element using AJAX, the Javascript created on $(document).ready
isn't working on it, which makes sense because it was created after the document ready. But what do I use to catch newly created elements?
This is the function in question, for all the buttons with .additem
on it when the page is loaded, it works perfectly, but when the new button is created with .additem
it doesn't work at all.
So I believe the javascript isn't being called on the new element. I've done several tests and I'm confident that's the case, but of course I could be wrong.
$('document').ready(function(){
$('.additem').click( function(e) {
e.preventDefault();
console.log('test')
const category_id = $(this).attr('id');
const url = `/add_item/${category_id}/`;
const name = $(`.newitemname${category_id}`).val();
const price = $(`.newitemprice${category_id}`).val();
const description = $(`.newitemdescription${category_id}`).val();
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'name':name,
'price':price,
'description':description,
},
success:function(response) {
console.log('success', response);
$(`.itemlist${response['category_id']}`).append($(`
<li class="row">
<div class="fw-normal mb-0 col-8"> ${response['item_name']} </div>
<div class="col-3 text-muted pl-5" align="right">$ ${response['item_price']}</div>
<p class="fw-lighter lh-sm" style="font-size: 12px;"> ${response['item_description']} </p>
</li>
`));
},
error:function(response){
console.log('error', response)
},
});
})
I've tried $().click
but it doesn't apply to the newly created buttons for some reason.
It works on the elements that are already on the page just fine though.
I've also tried $().change()
but it creates multiple copies of the same script. So that when I click the button it does it +1 times everytime I click the button. Ending up creating like 5 of the same item everytime I click .additem
.