vinay
vinay

Reputation: 33

is it possible to programatically simulate the click on an <a href> tag using jquery?

can we programatically click on an a href tag using jquery? i have tried $('a#someid').click(); but this does not trigger anything.. although i am using $("a#someid").attr("href", "someurl") to set the href dynamically which works fine..

Also i tried giving window.location = "someurl", but when this is done.. the IE browsers security comes into play and asks for me to download file. which i need to avoid. if the same "someurl" is given as an href to an A tag the url is loaded without any IE securities..

Any help is very much appreciated..

Upvotes: 1

Views: 457

Answers (1)

Antonio Louro
Antonio Louro

Reputation: 518

Taken from : here

Using .trigger('click') will not trigger the native click event. To simulate a default click, you can bind a click handler like so:

$('#someLink').bind('click', function() {
  window.location.href = this.href;
  return false;
});

... where "someLink" is an actual selector of your choice.

You can then trigger that bound click handler if you want, based on some other interaction.

$('input.mycheckbox').click(function() {
  if (this.checked) {
    $('#someLink').trigger('click');
  }
});

Upvotes: 3

Related Questions