Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger link click on Ajax success

Tags:

jquery

ajax

I need to trigger a link click on Ajax success. The code that I currently have is:

jQuery.ajax({
//Ajax Options
success: function(value) {
    jQuery('.parent_selector').html(jQuery(value).find('.child_selector'));
    jQuery('.test-link').trigger('click');
},
error: function() {
    //alert(error);
} });

The Ajax part works fine and I am able to load the .parent_selector div with Ajax response data. After this I need to trigger a link click for which I have jQuery('.test-link').trigger('click'); in the above code. However, the link click is never triggered. To check, I moved jQuery('.test-link').trigger('click'); within jQuery(document).ready(function() to see whether the link is triggered on page load. But it does not work there as well. The next thing I tried was to put jQuery('.test-link').trigger('click'); within click event of another link, as below:

jQuery('section[role="main"]').on('click', '.another-link', function(e){
e.preventDefault();

jQuery('.test-link').trigger('click');

});

Voila!, it works within a click event of another link. So, I am really confused as to what am I doing wrong here. Why jQuery('.test-link').trigger('click'); does not want to play nice with Ajax success call?

like image 476
John Avatar asked Mar 14 '12 14:03

John


1 Answers

When you use:

$(".test_link").trigger("click")
// or
$(".test_link").click()

You are executing only onclick events of the links it can be by jQuery bind or onclick attribute, but it doesn't open the page what you have in href.

So if you want to open the link which you have in href you need to so something like following:

window.location = $(".test_link").attr("href");

Other reason I can think of is you are getting the link dynamically and after getting it you are not adding any handler on the click event. jQuery "live" can solve the problem, but I would prefer to use delegate if you know what the parent container is.

like image 171
gaurang171 Avatar answered Sep 16 '22 20:09

gaurang171