tags:

views:

395

answers:

3

Hi to everyone, well my problem is that, i have a form, which i want to validate the fields using jquery, if the data is correct i let the submit continue, if no i disable the default behavior by returning false(saw that in a tutorial, here).
so i used as i said the jquery syntax, when the document is ready, i registered for the click event of the button, the problme is that code never gets executed. i used firebug but no clue. nothing happens, so here is my code:

$('#submitBtn').click(function()
{
 var password1 = $('#form_password').val();
 var password2 = $('#form_password2').val();
 if( password1 != password2)
 {
  alert("the two passwords are not equal.");
 }
 return false; //to disable the default behavior of the submit btn
});
+3  A: 

The proper way of checking a form submission is to check the form's submit event, not the button's click event. Change that around and what you have should work, although as it is right now it is always doing return false; so the form would never be sent. This should do it:

$('#myform').submit(function() {
        var motPasse1 = $('#form_motPasse').val();
        var motPasse2 = $('#form_motPasse2').val();
        if(motPasse1 != motPasse2){
            alert("Les deux mot de passe ne sont pas identiques");
            return false; // cancel form submission if passwords don't match
        }
        return true; // return true if no errors
});

Finally, I hope you are not keeping the alert there for production purposes. :) There are much, much better ways to display user notifications than an alert. Check out this question for some suggestions, although something as simply as having an error <div> and fading it in is nicer than the ugly default browser alert box.

Paolo Bergantino
thanks but the problem, is that the form is sent every time i try. believe me, i wouldn't be asking for help if it's not the case.
abdelkrimnet
Did you already try binding it to the form's submit event? As I said, if you bind it to the button's click event it is not a reliable way to check it, as pressing enter will not fire the event.
Paolo Bergantino
using the submit event of the form, it works fine, thanks so much for your help.
abdelkrimnet
A: 

your problem is that you are always returning false it should look as follows:

$('#envoyerButton').click(function()
{
        var motPasse1 = $('#form_motPasse').val();
        var motPasse2 = $('#form_motPasse2').val();
        if( motPasse1 != motPasse2)
        {
                alert("Les deux mot de passe ne sont pas identiques");
                return false;
        }
        return true;
});
SilentGhost
+1  A: 

Since you said you are using a form, you could bind to the form's submit event:

$('form#id').submit(function(){
  // your validation code
});
TenebrousX