Reputation: 2605
I am using jQuery to set a data attribute filtername
on an onClick which works fine.
$('#tag-group ul').append('<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="'+filterGroup+'" data-filtername="'+filterName+'"></i>'+text+'</li>');
It renders out on the screen ok as
<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="location" data-filtername="Melbourne"></i> Melbourne</li>
I am then trying to pick it up again on another onClick but it comes back as undefined. When I console log $(this).text();
it works but when I console log $(this).data('filtername');
it is undefined. Is the dom hiding it if it is generated by jQuery?
$(document).on('click','#sau-filter-tags ul li', function(event){
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
Upvotes: 8
Views: 12256
Reputation: 275
You are targeting a data attribute on i
tag. So you have to create an event upon i
$(document).on('click','#sau-filter-tags ul li i', function(event){
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
Upvotes: 2
Reputation: 16777
You are accessing the attribute on your containing <li>
rather than the <i>
inside. Try the following:
$('#sau-filter-tags li').on('click', function () {
var i = $(this.firstElementChild)
var text = i.text()
var filterName = i.data('filtername')
console.log(filterName) //=> 'Melbourne'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="location" data-filtername="Melbourne"></i> Melbourne</li>
Upvotes: 1
Reputation: 5466
filtername
is attribute of i
tag in li.
You need to select i
tag :
$(document).on('click', '#sau-filter-tags ul li i', function(event) {
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
or you need to attach event to li and find I in this
, Example:
$(this).find('i').data('filtername')
Upvotes: 7