Reputation: 18103
This is what I got:
<form method="post" id="myform" class="myform">
<input type="submit" onclick="return claim();" name="submit" class="onsubmit" value="" />
</form>
function claim() {
var c = confirm('You sure?');
if (!c) {
return false;
}
var password = prompt("Please mention pw","");
if (password != null && password != "") {
$.post(
"/claim/",
{ partner_pwd: password },
function(data) {
if (data == '1') {
$('form').submit(function() {
alert('Handler for .submit() called.');
});
}
});
}
return false;
}
This works well, but my problem is that it won't submit the form. I tried both $('form').submit()
and $('#myform').submit()
inside the data == '1'
statement. I tried alert(1)
inside this if statement, and it displayed fine, I only need to make it submit the form, why wont this work?
Update:
Console says:
Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function jquery.min.js:3 f.event.trigger
Upvotes: 4
Views: 3800
Reputation: 12419
I had a similar problem except I was trying to submit the form from Javascript, not attach an onsubmit event handler. The issue turned out to be that the submit button on the form I was working with had its name="submit"...I suspect that was part of what caused the original poster's problem as well. When the form has a button named "submit", it creates a "submit" property on the form object, overwriting the usual value of the "submit" property, which is a function that submits the form.
See javascript submit() is not a function? for more details
Upvotes: 0
Reputation: 2960
You made the following mistakes:
'form'
is too general and returns an array. So change it to '#myform'
.return false;
. Even after successfully validating the form, this line blocked it. It should have been return true;
. This mistake was pointed out by @11684, but no one understood him and was downvoted by some.Anyways, here's the debugged code.
function claim()
{
var c = confirm('You sure?');
if (!c) {
return false;
}
var password=prompt("Please mention pw","");
if (password!=null && password!="")
{
$.post("/claim/", { partner_pwd: password },
function(data) {
if(data == '1')
{
$('#myform').bind('submit',function() {
alert('Handler for .submit() called.');
});
}
});
}
return true;
}
Upvotes: 4
Reputation: 3897
As Rory said, your code will only add an event handler. You need to do
$(form).submit()
with no parameters. If you want to attach a handler, and then trigger the event later, you can use
$(form).trigger('submit')
Upvotes: 0
Reputation: 337627
To raise an event, you call the relevent function without a parameter like this:
$('form').submit();
Your current code is simply adding a submit handler function to be executed when the form is submit, it is not actually submitting the form.
Upvotes: 3