Reputation: 1044
I am trying to retrieve data from a dynamically created element
at the click of a button.
The script generating the element is:
$('.dropdown-menu li a').click(function(){
var $this = $(this);
var dropdownid = $(this).data('value');
var surname=$(this).data('surname');
var middlename=$(this).data('middlename');
var firstname=$(this).data('firstname');
var attendees=$(this).data('attendees');
$('.attendees').append('<div class='+dropdownid+'>'+firstname+' '+middlename+' '+surname+'</div>'+'<button class='+dropdownid+' id=btn-deleteattendee data-id='+dropdownid+' class=remove>X</button>');
});
The script to retrieve the data upon a button click is:
$(document).on('click','#btn-createclass',function(){
$('.attendees').each(function(result){
console.log('attendees: ',result)
});
However the console is printing this:
attendees: undefined
I have also tried this:
$('.attendees').on('click','#btn-createclass',function(event){
console.log('createclass button clicked');
event.preventDefault();
var $this = $(this);
$('.attendees').each(function(event){
console.log('result ',$(this).data('id'));
});
but that isn't working either. Any help is greatly appreciated
Upvotes: 1
Views: 3952
Reputation: 388316
You need to iterate over the button elements in attendees
element which has the data-id
attribute.
You are trying to get the data-id
value from the attendees
element, which does not have that value
$('.dropdown-menu li a').click(function() {
var $this = $(this);
var dropdownid = $(this).data('value');
var surname = $(this).data('surname');
var middlename = $(this).data('middlename');
var firstname = $(this).data('firstname');
var attendees = $(this).data('attendees');
$('.attendees').append('<div class=' + dropdownid + '>' + firstname + ' ' + middlename + ' ' + surname + '</div>' + '<button class=' + dropdownid + ' id=btn-deleteattendee data-id=' + dropdownid + ' class=remove>X</button>');
});
$(document).on('click', '#btn-createclass', function(event) {
event.preventDefault();
var $this = $(this);
$('.attendees [data-id]').each(function(event) {
console.log('result', $(this).data('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="dropdown-menu">
<li><a data-value="1" data-surname="s1" data-middlename="m1" data-firstname="f1" data-attendees="a1">1</a></li>
<li><a data-value="2" data-surname="s2" data-middlename="m2" data-firstname="f2" data-attendees="a2">2</a></li>
<li><a data-value="3" data-surname="s3" data-middlename="m3" data-firstname="f3" data-attendees="a3">3</a></li>
<li><a data-value="4" data-surname="s4" data-middlename="m4" data-firstname="f4" data-attendees="a4">4</a></li>
</ul>
<div class="attendees"></div>
<button id="btn-createclass">Create</button>
Upvotes: 3