Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventDefault not working on anchor

I'm trying to log the click on an anchor that's being generated asynchronously.

The asynchronous call - which works perfectly fine - looks like this:

 $("#txt_search").keyup(function() {
    var search = $("#txt_search").val();

    if (search.length > 0)
    {
      $.ajax({
        type: "post",
        url: "<?php echo site_url ('members/searchmember') ;?>",
        data:'search=' + search,
      success: function(msg){
        $('#search_results').html("");
        var obj = JSON.parse(msg);

        if (obj.length > 0)
        {
          try
          {
            var items=[];   
            $.each(obj, function(i,val){                      
                items.push($('<li class="search_result" />').html(
                  '<img src="<?php echo base_url(); ?>' + val.userImage + ' " /><a class="user_name" href="" rel="' + val.userId + '">'
                  + val.userFirstName + ' ' + val.userLastName 
                  + ' (' + val.userEmail + ')</a>'
                  )
                );
            }); 
            $('#search_results').append.apply($('#search_results'), items);
          } 
          catch(e) 
          {   
            alert(e);
          }   
        }
        else
        {
          $('#search_results').html($('<li/>').text('This user does not have an account yet'));   
        }   

      },
      error: function(){            
        alert('The connection is lost');
      }
      });
    }
  });

The anchor I want to get to is <a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>'

I detect the click on these anchors with this function:

  // click op search results
  $("a.user_name").on('click', function(e) {
    e.preventDefault(); 
  });

The problem seems to be that the preventDefault is not doing anything... I've looked at most of the questions involving this problem on Stackoverflow and checked jQuery's own documentation on the topic, but I can't seem to find what's wrong. I've tried adding a async: false statement to the AJAX-call, because perhaps the asynchronous call might be the problem, but that didn't fix it.

like image 714
silvdb Avatar asked May 27 '13 11:05

silvdb


People also ask

What does preventDefault() do?

preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

What is event preventDefault() in angular?

See, the event.preventDefault is a javascript function and is independent of angular version. However the binding used for (ngSubmit) in angularjs will change but the event.preventdefault would remain the same. You can try passing $event on (click) of a button as a parameter of any function.Ex. (


2 Answers

Event does not bind with dynamically added element unless you delegate it to parent element or document using on(). You have to use different form of on for event delegation.

$(document).on('click', 'a.user_name', function(e) {
    e.preventDefault(); 
});

delegated events

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, Reference

like image 159
Adil Avatar answered Oct 06 '22 00:10

Adil


The .on() syntax you showed will only bind handlers to elements that match the selector at that moment - not to elements added in the future. Try this instead:

$("#search_results").on("click", "a.user_name", function(e) {
  e.preventDefault(); 
});

This binds a handler to the parent element, and then when a click occurs jQuery only calls your callback function if the actual target element matches the selector in .on()'s second parameter at the time of the click. So it works for dynamically added elements (as long as the parent exists at the time the above runs).

like image 24
nnnnnn Avatar answered Oct 05 '22 23:10

nnnnnn