Omar Juvera
Omar Juvera

Reputation: 12287

jQuery: Call a function

I have a button with a jquery code that clears all data from a from.

<button id="reset">Reset</button>

The jQuery code looks something like this:

$("#reset").click(function()
{
    $(':input').val('');
...LOTS and lots of more code...
    $("#id").focus();
});

ALSO, separete from button...I have an ajax/php, where if successful, I want it to call the $("#reset").click() function.
-I do not want to copy and paste the code.

How can I call that function?
This did not work:

$("#reset").click();

Here is a "dummy sample" of my ajax, just show what I want to do:

//AJAX
//#new
$("#add").click(function()
{
   //START:$.post
   $.post( "ajax.php" ,
      {...var...},

      function(msg)
      {
      if( msg == 1 )
      { //Successful

      ...code...
      $("#reset").click();
      ...more code...

      } //end: if
      else
      { ...else code...} //end: if.else
      }//end: $.post.function
   ); //END:$.post
}); //END:ajax

Upvotes: -1

Views: 332

Answers (3)

jbabey
jbabey

Reputation: 46647

Calling $('#reset').click(); "should" work. Are you calling the click before attaching the click event handler? Or maybe you are attaching the event handler to the element before it exists on the page?

Upvotes: 1

Ilia G
Ilia G

Reputation: 10211

Simply calling click() should work. If not, then look at trigger

On a more general note - why would you not use form's standard reset method?

Upvotes: 0

Daff
Daff

Reputation: 44205

You can use .trigger() to trigger an event:

$('#reset').trigger('click');

Upvotes: 3

Related Questions