user1941674
user1941674

Reputation: 43

Adding a alert to a button click

I have been trying to add a alert to my button which updates a users details in a database.

I have tried adding a onclick method directly to the button and using functions but it doesn;t seem to work.

My button is;

<input type="submit" id="profileclick" value="Update" class="button-link"/>

And I am submitting the form by: (if it is important)

<form id="profile" method="post" action="../script/updateUserDetails.php">

One of the ways I tried was

$('#profileclick').click(function(){
 alert('Your details have been updated');
 $('#profile').submit();
});

In all instances the details update but I do not receive a alert.

Upvotes: 2

Views: 7017

Answers (2)

user234932
user234932

Reputation:

$('#profileclick').click(function(e) {
    e.preventDefault(); // prevents the form from being submitted by the button
    // Do your thing
    $('#profile').submit(); // now manually submit form
});

EDIT:

Just a note. This won't prevent the form from being submitted by other means, such as pressing Enter inside a text field. To prevent the form from being submitted at all, you have to preventDefault() on the form itself, as given in the other answer.

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206593

$('#profileclick').click(function(){    
     alert('Your details have been updated');
     $('#profile').submit();
});


$('#profile').submit(function( e ){
         e.preventDefault();

         // ........ AJAX SUBMIT FORM
});

Or simply add a delay before you submit using setTimeout ...

$('#profileclick').click(function(){    
     alert('Your details have been updated');
     setTimeout(function(){
             $('#profile').submit();
     }, 2000);        
});

Upvotes: 3

Related Questions