views:

448

answers:

3

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.

+2  A: 

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)

Philippe Leybaert
+1  A: 

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

jfrobishow
+1  A: 

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.

Vincent Robert