user2989327
user2989327

Reputation: 75

Focus an input when it is not filled

How can I focus an input when one of them is not filled. Right now I have this: http://jsfiddle.net/jalxob/ahQLC

$('#form').submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
    $( ".email1" ).addClass( "focusred" );
    $( ".name1" ).addClass( "focusred" );
    return false;
}  });

It shows the red focus but in both inputs although one of them is filled.

Thank you guys

Upvotes: 0

Views: 77

Answers (3)

Ron
Ron

Reputation: 1931

Try this:

$('#form').submit(function() {
if ($.trim($("#email").val()) === "")
{
    $( ".email1" ).addClass( "focusred" ).focus();
}
if ($.trim($("#user_name").val()) === "")
{
     $( ".name1" ).addClass( "focusred" ).focus();
}
    return false;

});

Demo: Fiddle

Upvotes: 0

SobiborTreblinka
SobiborTreblinka

Reputation: 575

$('#form').submit(function () {
    var result = true,
        focus_class = "focusred",
        elements = $("input#user_name,input#email");

    elements.each(function (index, element) {
        var element = $(element);
        if ($.trim(element.val()) === "") {
            element.addClass(focus_class);
            result = false;
        } else {
            element.removeClass(focus_class);
        }
    })
    return result;
});

Update, better answer:

http://jsfiddle.net/SobiborTreblinka/6UgxJ/3/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

Try

$('#form').submit(function() {
    if ($.trim($("#email").val()) === "") {
        $( "#email" ).focus();
        return false;
    }
    if ($.trim($("#user_name").val()) === "") {
        $( "#user_name" ).focus();
        return false;
    }
});

Demo: Fiddle

Upvotes: 2

Related Questions