Reputation:
I have a function thats create a element dynamically:
$('#bookUserSeat').on('click', function(){
$('#seatBookings').append('<div class="alert alert-info"><a class="deleteSeat" data-seatNumber="' + $(this).data('seatNumber') + '"><i class="fas fa-trash"></i></div>');
$('#modalBookSeat').modal('hide');
});
Now I have a function that works on the on click event:
$('#seatBookings').on('click', 'a.deleteSeat', function(){
var seat = $(this).data('seatNumber');
$(this).parent('div').remove();
});
But the var seat is empty. How can I get the data attr from the dynamically created link?
Upvotes: 2
Views: 185
Reputation: 28621
-data
and data()
are case-sensitive.
However, the attribute gets converted to lower-case when you use .append()
, so you actually have data-seatnumber
and data("seatNumber")
which don't match.
Demo:
$("#mydiv").append('<div data-lowercase="lowercase" data-mixedCase="mixedCase">inner</div>');
console.log("lowerCase", $("#mydiv>div").data("lowerCase"));
console.log("lowercase", $("#mydiv>div").data("lowercase"));
console.log("mixedCase", $("#mydiv>div").data("mixedCase"));
console.log("mixedcase", $("#mydiv>div").data("mixedcase"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
As you can see, the data-
is added with mixedCase
but gives undefined
on .data("mixedCase")
- but works fine with .data("mixedcase")
(all lower).
Always use all-lower attributes for compatibility.
Upvotes: 1