views:

3747

answers:

4

I have a simple email address sign up form as follows:

<form action="" id="newsletterform" method="get">
      <input type="text" name="email" class="required email" id="textnewsletter"  />
      <input type="submit" id="signup" />
</form>

Here's what I want to be able to do:

  • Validate the form to look for an empty string or a incorrectly filled out email address one the user clicks submit or hits enter.
  • If one of the above happens (empty string etc), I would like to generate an error to let the user know.
  • Then once the user fills out a correctly formed email address and hits submit (or enter) I want the form to send the email address to wherever I specify in the jQuery code and then generate a little "Thank you for signing up notice", all without reloading the browser.

I have looked at too many tutorials and my eyes are pretty much aching at this stage, so please don't point me to any urls (I most likely have been there).

If someone could provide a barebone outline of what to do It would be so much appreciated.

+7  A: 

First, please be sure you do all of your validation on the server-side. I like to get my forms working without any JavaScript whatsoever. I am assuming you have done that much.

*ORIGINAL ANSWER

Then, change your "submit" element to a button element. On the OnClick of the button element, run a JavaScript function that validates. Lots of samples on how to do that as you know.

If the validation fails, send up alerts. If it is successful, use JavaScript to submit the form.

*NEW, TOOL USING ANSWER

You can also employ JQuery as (orip points out) and it's plugins to do this. They handle a lot of the hard work. Please make sure my comments are telling the correct story. this code also does the AJAX submitting.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <!-- Load JQuery on your page -->
    <script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;
    <!-- Load JQuery validation sytles and (rules?) on your page -->
    <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.css" type="text/css" media="screen" />
    <!-- Load JQuery validation plugin on your page -->
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"&gt;&lt;/script&gt;
    <!-- Load JQuery form plugin on your page -->
    <script type="text/javascript" src="http://jqueryjs.googlecode.com/svn/trunk/plugins/form/jquery.form.js"&gt;&lt;/script&gt;
  <script type="text/javascript" language="javascript">
    //Wait until the document is loaded, then call the validation.  Due to magic in JQuery or the plugin
    //  this only happens when the form is submitted.
  $(document).ready(function(){
     //When the submit button is clicked
     $("#signup").click(function() {
      //if the form is valid according to the fules
      if ($("#newsletterform").valid()) {
       //Submit the form via AJAX
       $('#newsletterform').ajaxForm(function() { 
        //this alert lets me know the submission was successfull
        alert("Thank you!"); }); 
       }
      })
  });
  </script>
    <!-- Just some styles -->
    <style type="text/css">
      * { font-family: Verdana; font-size: 96%; }
      label { width: 10em; float: left; }
      label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
      p { clear: both; }
      .submit { margin-left: 12em; }
      em { font-weight: bold; padding-right: 1em; vertical-align: top; }
    </style>  
</head>
<body>
    <form action="" id="newsletterform" method="get">
     <!-- The classes assigned here are where the validation rules come fome.  
     This is required, and it must be an email -->
     <input type="text" name="email" class="required email" id="textnewsletter"  />
     <input type="submit" id="signup" />
    </form>
</body>
</html>

This isn't the tightest code you could write, but it will serve as an example.

MrChrister
Thanks for the reply.MY Newsletter service will provide the server side validation, so that's not a problem. Code examples would be great!
Keith Donegan
I stole that almost wholesale from the page orip pointed out.
MrChrister
Holy Moly, thanks!Quick question, where would I fill in the url to process the form in JQuery (eg, recieve the email address) ?
Keith Donegan
It is based on the action of the form.
MrChrister
+4  A: 

Use the jQuery Validation Plugin.

With it you don't need to modify your form - it will only be submitted if validation passes. It could save you a lot of time and complexity.

Edit:

To prevent the page reloading, either use the plugin's "submitHandler" option to submit yourself:

$('#myform').validate({
   // ...
   submitHandler: function() { alert("submitted"); }
});

or use the jQuery Form Plugin that converts your form submission to an AJAX submission - the Validation plugin integrates with it.

orip
That plugin is interesting. Thanks.
ayaz
Thanks for your help orip.I have tried it, validated it fine, but I can't seem to make the form submit without reloading the page?
Keith Donegan
Did you provide a real "action" in your real code?
MrChrister
Well I can alright.. but as I said I want the form to submit without the browser reloading, here is a perfect example of what I am trying to achieve: http://www.vouchercodes.co.uk/ - see the newsletter under the nav, thanks
Keith Donegan
@keithdonegan21, added links
orip
A: 

Thanks for all your help guys.

I have a solution that works perfectly the way I want (had to hire somebody :) - Anywho, for anybody else that needs it, here you go:

$(document).ready(function () {
      $('#textnewsletter').click(function () 
      {
            if($('#textnewsletter').val()=='Your email address')
                  $(this).attr("value",'');
      });

      $('form#newslattersub').submit(function () 
      {
            if(!isEmail($('#textnewsletter').val() ))
            {
                  $('p.idmsg').html('<span class="error">Please enter a valid email             address</span>').hide().fadeIn("slow");

       }
       else{
        $.post($('form#newslattersub').attr('action'), { email:$('#textnewsletter').val() },function(data){
            $('p.idmsg').html('<span class="success">Thanks for signing up! Please check your email for confirmation!</span>').hide().fadeIn("slow");
          //alert("server return " + data);
        });


       }
       return false;


      });

     });
Keith Donegan
A: 

tank you admin betufl

hit