Mbrouwer88
Mbrouwer88

Reputation: 2282

Validating fields when submitting form Jquery

I am really new to Jquery, but want to learn it. I came quite far with the tutorial all over the web, but now I want to validate a form before submitting it, and I can't find a simple example for this.

I have a form:

<form id="testform">
<input name="test" type="input">
<input type="submit" value="TEST">
</form>

I have this function:

$(document).ready(function() {
        $('#testform').submit(function(){


            $.get('test.php', $(this).serialize(), function(data){
                $('#test').html(data);
            });             
            return false;
        });
    });

Now what I want is quite simple, make the background color of the name field RED of it is empty. Please explain how to do this!


Looked at your answer, and it does not seem to work. When hitting the submit button, nothing happens, only the form clears.

Upvotes: 1

Views: 609

Answers (2)

e-barnett
e-barnett

Reputation: 75

As a fellow jquery newbie, I would say a couple of things here:

First, if you're just going to validate a couple of little things, you should absolutely write your own code. It'll be much lighter than using a plugin (probably...)

However, if you're validating quite a lot, you might want to look into jquery validation plugins (like http://bassistance.de/jquery-plugins/jquery-plugin-validation/) as these can make life a lot easier.

(Also, I'm sure you know this already, but don't forget the server-side validation, as client-side can fail!)

Happy coding!

Upvotes: 0

Ram
Ram

Reputation: 144669

try this:

$('#testform').submit(function(e) {
      if ($('input[name=test]').val() == "") { // if the input is empty
           $('input[name=test]').css('background-color','red')
           return false
      } else {
         $.get('test.php', $(this).serialize(), function(data){
              $('#test').html(data);
         });             
      }
      return false
});

Upvotes: 2

Related Questions