Reputation: 104
I have problem when i get data-id
in a href from ajax response, response always undefined
.
$("#loader_ekpresi").show();
$.ajax({
url:"<?php echo site_url() ?>Home/get_ekspresi",
type:'GET',
dataType: 'json',
data: {page:page}
}).done(function(response){
$.each(response, function( key, value) {
$('#gallery_show_ekpresi').append('<div class="item-box-gallery-4">'+
'<input type="hidden" id="url_ig" value="'+value.attachment_link+'embed/captioned">'+
'<a href="#" id="get_url" data-id="'+value.attachment_link+'embed/captioned" data-toggle="modal" data-target="#popup_gallery_modal">'+
'<img src="'+value.attachment_link+'media/?size=l">'+
'</a>'+
'</div>');
});
});
$('#get_url').click(function() {
var gallery_modal = $(this).attr('data-id');
alert(gallery_modal);
});
always got undefined
Upvotes: 0
Views: 988
Reputation: 796
Use classes instead of id, u are appending in loop.
$("#loader_ekpresi").show();
$.ajax({
url:"<?php echo site_url() ?>Home/get_ekspresi",
type:'GET',
dataType: 'json',
data: {page:page}
}).done(function(response){
$.each(response, function( key, value) {
$('#gallery_show_ekpresi').append($('<div class="item-box-gallery-4">'+
'<input type="hidden" class="url_ig" value="'+value.attachment_link+'embed/captioned">'+
'<a href="#" class="get_url" data-id="'+value.attachment_link+'embed/captioned" data-toggle="modal" data-target="#popup_gallery_modal">'+
'<img src="'+value.attachment_link+'media/?size=l">'+
'</a>'+
'</div>'));
});
});
$('.get_url').click(function() {
var gallery_modal = $(this).attr('data-id');
alert(gallery_modal);
});
Upvotes: 2
Reputation: 32354
Delegate your click event
$('#gallery_show_ekpresi').on('click','#get_url',function() {
var gallery_modal = $(this).attr('data-id');
alert(gallery_modal);
});
demo:
var response = [{
attachment_link: '1'
}, {
attachment_link: '2'
}]
$.each(response, function(key, value) {
$('#gallery_show_ekpresi').append('<div class="item-box-gallery-4">' +
'<input type="hidden" id="url_ig" value="' + value.attachment_link + 'embed/captioned">' +
'<a href="#" id="get_url" data-id="' + value.attachment_link + 'embed/captioned" data-toggle="modal" data-target="#popup_gallery_modal">' +
'<img src="' + value.attachment_link + 'media/?size=l">' +
'</a>' +
'</div>');
});
$('#gallery_show_ekpresi').on('click', '#get_url', function() {
var gallery_modal = $(this).attr('data-id');
alert(gallery_modal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="gallery_show_ekpresi"></div>
Upvotes: 3