jQuery on-click event empty

jquery each
jquery empty
jquery append
jquery remove class
jquery onclick call function
jquery ::after click event
jquery selector
jquery empty not working

I'm trying to read an attribute in my JavaScript-Function, so I can then further call a DELETE via AJAX with this attribute, but I already fail with retrieving the attribute by, what appears to me as, random. (jQuery version used for that is 3.2.1)

The "button" to start that chain (also already tried without the href and with href="#"):

UPDATE: Since it appeared as a comment, I indeed have something within the a-tag

<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
    <i class="fa fa-trash"></i>
</a>

My JavaScript:

$(document).ready(function(){
    $('.delete-record').on('click', function(e){
        $target = $(e.target);
        var id = $target.attr('data-id');
        if(confirm('Entry with ID ' + id){
           //AJAX
        }
    });
});

During testing with the confirm, I found out that my ID is sometimes set to undefined. Sadly I have no clue how this sometimes works and shows me the ID, and sometimes not.

Is there a solution to make this work with every click and not only about 24 out of the 42?

The issue is that when you click the icon inside the hyperlink, that the event bubbles up to the click handler. Inside the click handler, event.target will then refer to the icon element, which does not have the data-id attribute.

So the solution is to either:

1) Move the click event onto the icon and then make sure the hyperlink does not have any padding or other CSS styles that make the <a> clickable without also clicking the <i>.

2) Or check for which node was clicked inside the event:

    var $target = $(e.target);
    var id = $target.prop('tagName') === 'I'
        ? $target.parent().attr('data-id')
        : $target.attr('data-id');
    if (!id ) {
        console.error( $target );
        throw new Error( 'cannot find the correct id for target' );
    }
    else {
        var is_correct_id = confirm( 'Entry with ID ' + id );
        if ( is_correct_id ) {
            //createAjaxCall( 'DELETE', 'somePath', id );
        }
    }

There are other methods to find the correct parent element, in case one day you change the structure and the icon is not an immediate child of the hyperlink anymore. But I don't use JQuery anymore, so I'll leave searching for the correct syntax for .findParent( 'a[data-id]' ) up to the implementer.

3) Or as you demonstrate, duplicate the id onto the icon. :)

.empty(), Hello, Person and person. Call empty() on above paragraph. Ajax · Global Ajax Event Handlers  jQuery click() Method jQuery Event Methods. Example. The click() method triggers the click event, or attaches a function to run when a click event occurs. Syntax.

The answer is actually based on Shilly's comment to the question.

Since I indeed got another element within my a-tag, the target was different depending on where I clicked the link/button. As an easy fix for that, I simply appended the ID to the i-tag as well:

<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
    <i class="fa fa-trash" data-id="5c25f547d42"></i>
</a>

Event Delegation, on( events [, selector ] [, data ], handler ). events. Type: String. One or more space​-separated event types and optional namespaces, such as "click" or  To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves. If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.

Did you tried to href="javascript" and also this could return list of elements so try to put the listener using an id like this

<a class="btn btn-light delete-record" id="deleteButton" href="" data-id="5c25f547d42" title="Delete">
$(document).ready(function(){
    $('#deleteButton').on('click', function(e){
        e.stopPropagation();
        $target = $(e.target);
        var id = $target.attr('data-id');
        if(confirm('Entry with ID ' + id){
           //AJAX
        }
    });
});

.unbind(), A string containing one or more DOM event types, such as "click" or "submit," or custom event names. handler. Type: Function( Event eventObject ). The function​  Commonly Used jQuery Event Methods $(document).ready() The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter. click() The click() method attaches an event handler function to an HTML element.

You should change your JS + HTML to this:

HTML

<button class="btn btn-light delete-record"
        data-id="5c25f547d42"
        title="Delete">
    Click me!
</button>

Your problem with using <a> is that you don't stop the defaul behaviour of the <a> tag - which is a link. It's just refreshing the page (if you leave href blank). Changing it to a button is much better, as it's .. well a button in principle.

jQuery

jQuery(document).ready(function($)
{
    $('.delete-record').click(function()
    {
        let id = $(this).attr('data-id');
        if (confirm('Entry with ID '+ id)) {
            //whatever
        }
    });
})

You don't need to get the target, just use $(this) to get the clicked element's data-attribute. Then carry on script as normal

event.target, This property is very useful in event delegation, when events bubble. Examples: Display the tag's name on click. 1. 2. 3. This method is a shortcut for .on( "click", handler ) in the first two variations, and .trigger( "click" ) in the third. The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. For example, consider the HTML:

You could try specifying the role of the anchor tag to button. Then you won't have to worry about specifying the href as the anchor tag will be treated as button. https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role

Element: click event, An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while  The blur event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the blur event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping blur to the focusout event in its event delegation methods, .live() and .delegate().

The Dangers of Stopping Event Propagation, This bug happens because the Bootstrap code responsible for closing the dropdown menu is listening for click events on the document. But since jquery-ujs​  .one( events [, data ], handler ) Returns: jQuery Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

jQuery empty() Method, The empty() method removes all child nodes and content from the selected elements. Tip: To remove the elements without removing data and events, use the  Books. Learning jQuery Fourth Edition Karl Swedberg and Jonathan Chaffer jQuery in Action Bear Bibeault, Yehuda Katz, and Aurelio De Rosa jQuery Succinctly Cody Lindley

Should I leave href empty when implementing click events via jQuery?, Links with an empty href attribute are valid, as explained in RFC2396: 4.2. Same-​document References. A URI reference that does not contain a URI is a  To remove elements and content, there are mainly two jQuery methods: remove () - Removes the selected element (and its child elements) empty () - Removes the child elements from the selected element jQuery remove () Method

Comments
  • Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
  • If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
  • Why do you declare the $target as global variable? Make it a local variable and try again?
  • @JackBashford Sadly no (console) errors to work with :/
  • Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
  • Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)