user663724
user663724

Reputation:

Fetching the attribute on class is not working using JQuery

When i click on the Edit button , the data attribute value as undefined, please let me know how to resolve this?

 <div role="main" class="ui-content oms-content">
            <div class="myactivelabelsWrap">
                <div data-role="collapsible" data-inset="false">
                    <h3>Heading 1<a class="icon-pencil-1 labelEditIcon" data_attr="123" >Edit</a></h3>
                    <ul data-role="listview" class="labellistUL">
                        <li class="labellist">
                            <div class="leftlable">
                                <p>Content here</p>
                            </div>
                        </li>
                    </ul>
                </div>
                <div data-role="collapsible" data-inset="false">
                    <h3>Heading 2<a class="icon-pencil-1 labelEditIcon" data_attr="345" >Edit</a></h3>
                   <ul data-role="listview" class="labellistUL ">
                        <li class="labellist">
                            <div class="leftlable">
                                <p>Content here</p>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>

document.addEventListener(
    'click',
    function(event){
        if( $(event.target).is('.labelEditIcon')){
            var address_label = $(this).attr('data_attr');
            alert(address_label);
            event.stopPropagation();
        }
    },
    true // Capture event
);

http://jsfiddle.net/tdzfhzjy/15/

Upvotes: 0

Views: 48

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

The problem is, $(this) refers to jquery object of document and not of target element.you need to target the element using event.target:

  var address_label = $(event.target).attr('data_attr');

Demo

Suggestion:

Attaching the click event to whole document is bad practice. You should rather attach the click event to only required element:

$('.labelEditIcon').click(function(e){
    alert($(this).attr('data_attr'));
    e.stopPropagation();
});

Working Demo

Upvotes: 1

Related Questions