Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data attribute is returning undefined

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
        });
like image 846
ottz0 Avatar asked Dec 07 '16 02:12

ottz0


3 Answers

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')

like image 113
Ajay Narain Mathur Avatar answered Nov 06 '22 18:11

Ajay Narain Mathur


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
});
like image 24
Jaber Avatar answered Nov 06 '22 18:11

Jaber


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>
like image 1
gyre Avatar answered Nov 06 '22 19:11

gyre