Brad Hazelnut
Brad Hazelnut

Reputation: 1621

jquery validation on input

I have a form that i am trying to validate. I have a field that i want to make sure is required. I have the following code for the field:

<p>
   <label for="lf">Name: </label>
   <input class="lf" name="name" type="text"/> 
   <span id="name_error" class="validate_error">Please enter a valid name!</span>
</p>

I want to be able to first off if they click in the box and don't type anything and then go to a different box, i want the span tag to show and also if they hit submit and didn't type anything.

I have the following jquery code, but it always shows the span tag no matter what.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){

    <!--Name can't be blank-->
    $('#name').on('input', function() {
        var input=$(this);
        var is_name=input.val();
            if(is_name){
                $("#name_error").hide();
            }else{
                $("#name_error").show();
            }
    });

});
</script>

Upvotes: 0

Views: 638

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

You are targeting with id, but the element does not have an id.

Either set id="name" on the input element

<input class="lf" id="name" name="name" type="text"/>

or use another selector input[name="name"] when targeting it.

$('input[name="name"]').on('input', function() {

(additionally, that html comment should not be there or it should have a // at the beginning)

Upvotes: 2

Kolby
Kolby

Reputation: 2865

Try this:

 $('#name').on('blur', function() {
    var input=$(this);

    var is_name = input.val();

     if(is_name){
         $("#name_error").hide();
     }else{
         $("#name_error").show();
     }
 });        

http://jsfiddle.net/UR8m4/1/

You had a few problems, first, you didn't have the id #name on your input. Second, you need to hide the error with css to begin with. Third, you need to bind to the blur event.

Upvotes: 1

Bogdan Martinescu
Bogdan Martinescu

Reputation: 87

I think it should be

$('input.lf').on('blur', function() {
    var input=$(this);
    var is_name=input.val();
        if(is_name){
            $("#name_error").hide();
        }else{
            $("#name_error").show();
        }
});

you have no name id on the input, sorry just noticed and fixed

Upvotes: 1

Related Questions