Reputation: 2444
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?
Upvotes: 3
Views: 41305
Reputation: 1028
If both return false
and event.stopPropagation()
don't work, try the following method. Using .on()
will make the submit function accessible. Once you change the .submit()
to .on("submit"..)
, you can either use return false
or e.stopPropagation()
.
$(document).on("submit", "input#send", function(event) {
event.stopPropagation();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false; });
Upvotes: 0
Reputation: 6192
I believe the submit event is for the form element. For an input[type='button'] you might want to use the click event.
Upvotes: 2
Reputation: 75690
'add.php'
id
attribute of the form which contains input#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;
});
Upvotes: 1
Reputation: 76003
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();
});
Upvotes: 7
Reputation: 10830
If you're using preventDefault I assume that means you do NOT want the default submit action. I would just use a different event instead of using .submit. To me, it's not the submit action that you want to intercept, but rather the click that would normally cause the submit.
$('#inputSend').on('click', function(event) {
event.preventDefault();
//the rest
});
Upvotes: 0
Reputation: 154958
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();
// ...
});
Upvotes: 10
Reputation: 764
Try using return false instead
$("input#send").submit(function(event) {
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false;
});
Upvotes: 0