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
        });
                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')
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
});
                        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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With