Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tiffany McAllister
Tiffany McAllister
25,806 Points

JQuery Input Validation

I have a very simple JQuery validation script as below:

var requiredInputs = $('input, textarea');

requiredInputs.blur(function () {
    if ($(this).val() == ""){
        $(this).prev().fadeIn();
    }
}).keyup(function () {
    if ($(this).val() == ""){
        $(this).prev().fadeIn();
    } else {
        $(this).prev().fadeOut();
    }
});

I want it to fadein a span with an error message when the input is blank once the input no longer has focus and to also fadeout the span when something is typed into the input. This all works great when using the mouse to click in and out of the inputs, however, when using the tab key to cycle through the inputs, the span appears as soon as the input has focus. I'm assuming this has something to do with the keyup function, but I'm unsure how to get it to do what I want.

Can anyone help?

1 Answer

Gergő Bogdán
Gergő Bogdán
6,664 Points

The function in the keyup handler can receive parameters, and it gets the pressed key, you can check for TAB there and only fadein/fadeout when the tab was not pressed. You'll have to check the ascii code of TAB key.