0

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.

1
  • You are trying to trigger a form submit but the code you have bound to the submit is not firing? Is that it? Commented Jun 2, 2009 at 17:07

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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");

Comments

-1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.