alin dradici alin dradici - 29 days ago 5
HTML Question

cannot get data-value from paragraph

I have a very frustrating issue. I have two kind of paragraphs in a div , a built in one like you see below

<div >
<table id="box">
<thead>
<tr>
<td><p class="linkin" data-value="test22">test</p></td>
</tr>

</thead>
<tbody>

</tbody>
</table>
</div>
</div>


And fetched ones like this:

$('.menu').on('click', function(){
$('#box').toggle('slide').show();
$.ajax({
url:'fetchsubmenu.php',
data : {nume : $(this).attr('data-value')},
dataType : 'json',
success:function(data){
console.log(data);// process your response
showObjects(data);
}
});
});


function showObjects(obiecte){

$('#box tbody').html('');
for(var i=0; i<obiecte.length; i++){ //Functia care arata obiectele
var aparat = obiecte[i];
$('#box tbody').append(getRow(aparat));
}
}

function getRow(aparat){


var row = '<tr>'+
'<td>' + '<p class="linkin" data-value='+aparat.id+' >'+aparat.nume+'</p>' + '</td>'+ //functia care le aranjeaza
'</tr>';

return row;
}


The problem is that when I want to get the data-value attribute like this:

$('.linkin').on('click',function(){
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function(){
console.log();
alert('success');
}
});
});


the built in paragraph works just fine, I get the data-value attribute , but the fetched paragraphs don't work, I am not able to get any attributes.
Sorry for my english.

Answer

This is happening because the event listening is only being bound to objects present when the code runs. That would explain why objects that are fetched after the code runs do not work as anticipated. This can be fixed by simply binding to the document.

$(document).on('click', '.linkin', function() {
     $.ajax({
        url:'test.php',
        dataType:'JSON',
        data : {id : $(this).attr('data-value')},
        success:function() {
          alert('success');
        }
      });
 });
Comments