Mark
Mark

Reputation: 33671

Jquery triggering a click

I've been trying to use jquery to trigger a click.

I've discovered that triggered clicks, like this: $(button).trigger('click'); do not follow hrefs. I've been trying to make an ajax submission by triggering the submit button, but no go.

I know I can submit directly. But is there any way of triggering the button? Thanks.

Upvotes: 0

Views: 6501

Answers (4)

jstaab
jstaab

Reputation: 3885

Another alternative, tested in Chrome, Firefox, IE6, IE8:

window.location = $('a').trigger('click').href('attr');

I ended up using this because we have default jquery link handling on click events, but we also wanted to trigger an actual link visit (the link could be either a hash or a cross-domain link).

Upvotes: -1

Vincent Robert
Vincent Robert

Reputation: 36150

jQuery does not trigger the native "click" on A elements on purpose. I don't know why.

But you can use the technique they use to trigger the link yourself:

$link[0].click(); // extract the native DOM element and trigger the click

This is untested but it is extracted from jQuery source code and should work.

Upvotes: 8

jfrobishow
jfrobishow

Reputation: 2895

Not sure why you would want to do this, but I've tested it here with the following and it worked.

<form id="frm" action="#">
 <input type="submit" id="btnSubmit" />
  ...
  ...
</form>

Call this -> jQuery("#btnSubmit").trigger("click");

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171914

I don't see why you would need to do that. Maybe you want the label of the submit button to be submitted with the form (so your server code knows what button is pressed). In that case, you can do something like this:

var $form = $("form"); // your form
var $button = $(":submit",$form); // your button
var $hidden = $("<input type='hidden' />");

$hidden.attr("name",$button.attr("name"));
$hidden.val($button.val());

$form.append($hidden);
$form.submit();

I'm sure this can be optimized, but it will work (it will simulate a "real" submit using the submit button)

Upvotes: 2

Related Questions