Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove existing and add onsubmit in form using jquery

Given this HTML to create a form:

<form name="search" id="myForm" onsubmit="return existingfunc()" method="post">
    <input type="submit" value="Search" title="Search">
</form>

I can change the form's name via jQuery using $('#myForm').attr('name','newname').

Is it possible to change the form's onsubmit function?

like image 218
mymotherland Avatar asked Aug 10 '11 08:08

mymotherland


2 Answers

To just change the form onsubmit event you could do this:

 $('#myForm').attr('onsubmit', 'return somethingElse()');

But you probably want to remove the form's onsubmit attribute then add a new event using jQuery (note: unbind() will remove only event handlers attached by jQuery):

 $('#myForm').removeAttr('onsubmit').submit(function(e) { /* your logic here */ });
like image 156
Jeromy French Avatar answered Oct 19 '22 23:10

Jeromy French


You can remove an existing event using jQuery's unbind function, eg:

$('#myForm').unbind('submit');

will remove all onsubmit events from #myForm. Then you can add a new event using normal jQuery:

$('#myForm').submit(function(e) { /* your logic here */ });
like image 33
beeglebug Avatar answered Oct 19 '22 21:10

beeglebug