views:

192

answers:

4

I am trying to validate a form in that if there is no text in an input field, an error icon pops up... and if ANYTHING is in the input a success icon pops up. There are no true validation methods being used. You can see the form here.

As you can see, when you type something in the first field and press tab, the icon pops up correctly, but it will not work on any of the fields after the first. Here is my jquery:

<script type="text/javascript">
     $(function(){
     var field = document.getElementById('myFormField');
     var icon = document.getElementById('myIcon');

     field.onchange = function(){
      icon.src = this.value ? 'success.png' : 'fail.png';
     };
     });
</script>

I dont know how to make this work on all the input fields, but Im sure it is a simple fix. My HTML is set up just like this:

<input type="text" class="name" name="name" tabindex="1" id="myFormField"  /><img id="myIcon" />

the id myFormfield triggers the icon, and the class "name" triggers the background on click. I supposed I should stick with the class and try to use it as a part of this solution. Any Ideas?

+5  A: 

You're not really using the power of jQuery. Try something like this:

$(function(){
    $(':text,:textarea').bind('change, blur',function(){
        $(this).next('img').attr('src',this.value ? 'success.png' : 'fail.png');
    });
});
PetersenDidIt
Thanks! that works great, however, it doesnt seem to be working on the textarea. I reduced the width to make room for the icon, but its not appearing. Ay ideas?
JCHASE11
Updated the selector to also select textareas. Check out the jQuery docs http://docs.jquery.com/Selectors
PetersenDidIt
A: 

If you're using jQuery, the easiest method would be:

$('input').change( function() {
  icon.src = $(this).val() ? 'success.png' : 'fail.png';
});

You may wish to replace $('input') with a more specific selector such as $('input[type="text"]').

DisgruntledGoat
A: 

well, you're using jquery, but not using jquery. You should probably have something like

$("input").bind('blur', function(){
    if ($(this).val() == ''){
        $(this).siblings('.icon').attr('src', 'fail.png');
    }
    else{
         $(this).siblings('.icon').attr('src', 'success.png');
    }
}

put that inside your $(function(){ }); block.

what it does is check to see if the text is blank when the input loses focus, then sets it's sibling (that has a class='icon' to success or failure.

contagious
+3  A: 

You seem to be just starting out with jQuery. Well, once you get over the first little bit of the learning curve, prepare to have your mind blown! One of the most powerful features of jQuery is the ability to select elements in your document using CSS selectors.

allinputs = $("input"); // Selects all input elements in your DOM
allrequiredinputs = $("input.required"); //Selects all input elements with a class of "required" in your DOM
allrequireds = $(".required"); //Selects all elements regardless of the tag name that have a class of "required"

There are other answers in this thread that answer your question perfectly well so I won't try and duplicate them here. However, I do have a suggestion which might work better for you. Instead of loading a different image into the DOM when the state of the form changes, why not use a sprite with "good", "no good" and "blank" states and simply update the class of your validation element when the input field changes. This way, all possible states of your validation element are pre-loaded so feedback is instant rather than after the second or so it takes to download the image.

To learn more about sprites, read these:

You could then do something like this:

//CSS

.validation {
display: block;
float: left;
width: 10px;
height: 10px;
}
.validation.blank {
background: none;
}
.validation.good {
background: url(mysprite.gif) 0px 0px;
}
.validation.nogood {
background: url(mysprite.gif) 0px 10px;
}

//HTML

<form id="myForm" ... >
    <div id="contactform_namerow">
        <label for="name">Name</label><input type="text" id="name" name="name" />
        <div class="validation"></div>
    </div>
</form>

//jQuery

$(function(){
    $('#myform input, #myform textarea').bind('change',function(){
        if($(this).val == ""){
            $(this).siblings(".validation").addClass("nogood").removeClass("good");
        } else {
            $(this).siblings(".validation").addClass("good").removeClass("nogood");
        }
    });
});

You can further optimise this by putting class names denoting how each field should validate on each input element. That way you can write some code that would validate email addresses by setting something like <input type="text" id="myemail" name="email" class="email"> and selecting all elements like that in jQuery by going $('input.email')... Also, I'm sure there is a toggleClass function somewhere but I was too lazy to look it up.

But... the great thing about jQuery is the HUGE number of plugins available. This one is my personal favourite: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Once you learn how to use the plugin properly, I'm sure you'll find that it will do everything you want to acheive here and more!

Hope this helps and good luck!

Iain

Iain Fraser
lain. I cant thank you enough for this. I am just learning jquery and im so excited. Im not giving yhou the check because I got my answer from above, but youve provided some great insight and I thank you. I think I will use the sprite technique. Thanks for your help
JCHASE11
No problems JCHASE11, glad to have been of some help to you. Full disclosure: I am a MASSIVE jQuery fanboy and am keen to help anyone who wants to use it. At the moment I'm learning C# and the amount of help I've gotten from SO has been invaluable. It's nice to be able to give back :)
Iain Fraser