4

I'm fairly new to Jquery, so this might be a simple problem, but is there a way to hide the submit button on a form until all the fields have been validated.

The validation would need to be an 'as you type' solution. Basically I have 3 fields - first name, last name and e-mail. I'd like the submit button to stay hidden until the two 'name' fields have been filled in and a valid e-mail address has been entered into the e-mail field.

The form itself uses AJAX to input the form data into a database. The form is in a lightbox which should automatically close once the submit button is clicked.

You can see an example here: http://testing.xenongroupadmin.com/whatis/pfi

Ignore the 'Close this Window' link - that's just there for my convenience and will be removed in the final version.

Below is the HTML code for the form, followed by the JQuery/AJAX submission code:

<form id="registerform" action="thanks.php" method="POST">
 <ul id="inputform">
  <li>
   <label for="firstname" id="firstnamelabel">First Name</label>
   <input type="text" name="first_name" id="fname" class="registerboxes" />
  </li>
  <li>
   <label for="lastname" id="lastnamelabel">Last Name</label>
   <input type="text" name="last_name" id="lname" class="registerboxes" />
  </li>
  <li>
   <label for="email" id="emaillabel">E-mail Address</label>
   <input type="text" name="emailbox" id="email" class="registerboxes" />
  </li>
 </ul>
 <input type="submit" value="Submit" id="emailbutton" />
</form>

And the Jquery:

$(document).ready(function(){
 $("form#registerform").submit(function() {
  var fname     = $('#fname').attr('value');
  var lname     = $('#lname').attr('value');
  var email     = $('#email').attr('value');    

 $.ajax({
  type: "POST",
  url: "post.php",
  data: "fname="+ fname +"& lname="+ lname +"& email="+ email,
  success: function(){

 $('div#register-panel, div#lightbox').fadeOut(300);
   }
  });
  return false;
 });
});

Thanks!

Chris
  • 1,863
  • 5
  • 30
  • 43
  • ho do you validate the inputs? – Ram Jul 27 '12 at 15:29
  • Am planning to use jquery validation plugin, but haven't written the code yet – Chris Jul 27 '12 at 15:31
  • 2
    Why don't you use .val() instead of attr('value'); ? – Oscar Jara Jul 27 '12 at 15:35
  • Can do. Still need to work out how to do make the submit button appear, though. – Chris Jul 27 '12 at 15:37
  • Well I'd likely run a validation check on a per field basis, based on blur, where on the last field upon successful validation of that field, run an addition check against all fields, where if it comes back successful for all, show the button. – chris Jul 27 '12 at 15:52

3 Answers3

6

http://jsfiddle.net/nickaknudson/KnZaq/

$(document).ready(function() {
    $('#emailbutton').hide();
    $('input').change(function(e) {
        if ($('#fname').val() && $('#lname').val() && $('#email').val() && validateEmail($('#email').val())) {
            $('#emailbutton').show();
        }
    });
});

var validateEmail = function(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
};​

UPDATE

Sorry, it may have been buggy on that version of the fiddle. Try again? http://jsfiddle.net/nickaknudson/KnZaq/3/

RESOURCES

Community
  • 1
  • 1
nickaknudson
  • 4,769
  • 2
  • 15
  • 16
  • 3
    Good solution, Nick! Chris, if you go ahead with this one, just remember that you are keeping all of your validation on the front-end, so you should still validate on the backend. Otherwise, you may have people simply change the page's css in their browser and submit the form without entering any information (blank and invalid submissions). Also, you may want to wait for the AJAX to post back an indication that the submission was valid and completed successfully before you close the window, for the same reason. – Zachary Kniebel Jul 27 '12 at 16:26
  • This looks great, just one small problem - the var validateEmail has a bug somewhere, so it knocks out all my javascript! I wish I knew how to fix this myself but I the "var re = /^(( etc." line is a foreign language to me! – Chris Jul 27 '12 at 16:47
  • I would recommend using `disabled="disabled"` rather than hiding the submit button. As Zachary pointed out, this does not stop users from removing that attribute manually and then submitting an invalid form, so do make sure you do server-side validaiton. – Wex Jul 27 '12 at 17:09
  • In other words, `$('#emailbutton').hide()` changes to `$('#emailbutton').attr("disabled", "disabled")`, and `$('#emailbutton').show()` changes to `$('#emailbutton').attr("disabled", null)` – Wex Jul 27 '12 at 17:12
  • @Chris I'm not seeing any issues with loosing JavaScript following my code. http://jsfiddle.net/nickaknudson/KnZaq/4/ – nickaknudson Jul 27 '12 at 20:40
  • Hi Nick, the most up to date version (jsfiddle.net/nickaknudson/KnZaq/4) seems to have worked - thanks!!! – Chris Jul 29 '12 at 20:46
0

I don't know which validation plugin you're using but I assume it will return a true/false. Either in your ready handler or in the css set the display of the submit button to "none", then after you've validated it, use the JQuery show() method. Something like:

if (formIsValid) {
    $("#submitID").show();
}

Another, more user friendly option, would be to show the button but have it disabled until the form is valid, then enable it.

Dave

dsvick
  • 41
  • 5
0

Your form data is not so large, you can do something manually (I think) if you want to learn something new instead of using plugins and validations in javascript side.


Well, I prefer to validate things through server side, take a look at this:

Tested and working:

index.htm

<html>
<head>
<title>Get more information</title>
</head>
<style>
.error {
    color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){

    $('#emailbutton').on('click', function(){
        var fname = $('#fname').val();
        var lname = $('#lname').val();
        var email = $.trim($('#email').val());

        $.post('validate.php', {fname:fname, lname:lname, email:email}, function(data){
            if(data != 1) {
                var obj = $('#' + data + '_msg');
                if(data == 'fname') {
                    obj.html('Invalid first name.').addClass('error').show().fadeOut('slow');
                } else if (data == 'lname') {
                    obj.html('Invalid last name.').addClass('error').show().fadeOut('slow');
                } else if (data == 'email') {
                    obj.html('Invalid email.').addClass('error').show().fadeOut('slow');
                }
            } else if(data == 1) {
                $('#registerform').submit();
            }
        });
    });


});
</script>
<body>
<form id="registerform" action="thanks.php" method="POST">
 <ul id="inputform">
  <li>
   <label for="firstname" id="firstnamelabel">First Name</label>
   <input type="text" name="first_name" id="fname" class="registerboxes" />
   <span id="fname_msg"></span>
  </li>
  <li>
   <label for="lastname" id="lastnamelabel">Last Name</label>
   <input type="text" name="last_name" id="lname" class="registerboxes" />
   <span id="lname_msg"></span>
  </li>
  <li>
   <label for="email" id="emaillabel">E-mail Address</label>
   <input type="text" name="emailbox" id="email" class="registerboxes" />
   <span id="email_msg"></span>
  </li>
 </ul>
 <input type="button" value="Submit" id="emailbutton" />
</form>
</body>
</html>

validate.php

<?php 
if(isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email'])) {

    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $email = $_POST['email'];

    if(validateInput($fname, 2, 25)) {
        if(validateInput($lname, 2, 30)) {
            if(validateEmail($email, 5, 150)) {
                print(1);
            } else {
                print('email');
            }
        } else {
            print('lname');
        }
    } else {
        print('fname');
    }
}
function validateInput($value, $minlength, $maxlength) {
    $valid = false;
    try {
        if (strlen(trim($value)) == 0) {
            $valid = false;
        } else if (strlen(trim($value)) < $minlength || strlen(trim($value)) > $maxlength) {
            $valid = false;
        } else {
            $valid = true;
        }
    } catch (exception $e) {
        /* get exception: $e->getMessage() */
        $valid = false;
    }
    return $valid;
}

function validateEmail($email, $minlength, $maxlength) {
    $valid = false;
    try {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $valid = false;
        } else if (strlen(trim($email)) == 0) {
            $valid = false;
        } else if (strlen(trim($email)) < $minlength || strlen(trim($email)) > $maxlength) {
            $valid = false;
        } else {
            $valid = true;
        }
    } catch (exception $e) {
        /* get exception: $e->getMessage() */
        $valid = false;
    }
    return $valid;
}
?>

thanks.php

<?php 
if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['emailbox'])) {

$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['emailbox'];

echo $fname.' '.$lname.' '.$email;

// Do what you need with your data at this point, don't forget to sanitize values to insert them in your DB :-)

}
?>
Oscar Jara
  • 14,129
  • 10
  • 62
  • 94