event.preventDefault not working
Solution 1
A form has the submit event, not a button. Plus, an ID should be unique so tag#id
can just be #id
.
$("#theform").submit(function(event) {
event.preventDefault();
// ...
});
Solution 2
You need to bind to the form's submit
event or to the button's click
event and call event.preventDefault()
if you want to stop the form from submitting:
$('form').bind('submit', function (event) {
event.preventDefault();
});
$('form').find(':submit').bind('click', function (event) {
event.preventDefault();
});
Solution 3
I believe the submit event is for the form element. For an input[type='button'] you might want to use the click event.
Solution 4
- Add quotes around
'add.php'
- Change the selector in the first line to the
id
attribute of the form which containsinput#send
.
The advantage of handling the submit()
handler on the form rather than the click
handler on the input is that some forms can be submitted by pressing the enter key (when the user is focused on one of the form fields). If you don't have an id
attribute, add one or use a different jQuery selector to target the form tag.
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: data,
success: success,
dataType: dataType
});
return false;
});
Peter Stuart
My name is Peter. I am a web developer always seeking to learn and grow in my graft. I'm usually asking more than answering on here, but will help where and when I can
Updated on February 14, 2020Comments
-
Peter Stuart about 4 years
I have this simple code here, nothing too advanced.
$("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, success: success, dataType: dataType }); });
Whever I click on the "send" button, the
event.preventDefault
function doesn't work, and the page loads.Any ideas why?
-
Felix Kling over 12 yearsShould not make a difference.
-
Peter Stuart over 12 yearsThanks, that worked. May I ask, I used the click function on the button earlier, but it didn't seem to work that way either? Why is that?
-
Jasper over 12 years
return false
in a jQuery event handler is the same as callingevent.preventDefault(); event.stopPropagation();
-
Peter Stuart over 12 yearsI had tried that, it didn't work because of the ajax. it worked if I put it above the ajax code, but not after it. Thanks anyway :)
-
pimvdb over 12 years@Peter Stuart: What exactly do you mean? Putting
click
on thesubmit
button works too: jsfiddle.net/rKJJU. -
jessegavin over 12 years@PeterStuart I think it's because you didn't put quotes around
add.php
, see my answer below. I agree with @pimvdb's advice about putting the event handler on the form itself, because you can also invoke a form submit with theenter
key via the keyboard.