2

Hey I have a login form that when you click on the input the label move up, after focus out it checks if there is text in the input and if have the label stays up if dont the label comes down.

My code is:

$(function () {
    $('.loginForm .inputGroup input').focusout(function () {
        var text_val = $(this).val();
        if (text_val === "") {
            $(this).removeClass('has-value');
        } else {
            $(this).addClass('has-value');
        }
    });
});

The problem is when I click on login and it gives an error like username does not exist I want to keep the username on the input but when I do it the label stays on top of the text on the input.
How can I check on load if have text or not on the input?

Images to help understand the situation:

enter image description here enter image description here

JSFiddle: http://jsfiddle.net/16g7yhLf/

Cheers!

1 Answer 1

7

You can trigger the focusout event after registering the event handler so that the handler will get executed.

$(function () {
    $('.loginForm .inputGroup input').focusout(function () {
        var text_val = $(this).val();
        if (text_val === "") {
            $(this).removeClass('has-value');
        } else {
            $(this).addClass('has-value');
        }
    }).focusout();//trigger the focusout event manually
});

Demo: Fiddle


A shorter version can be

$(function () {
    $('.loginForm .inputGroup input').focusout(function () {
        var text_val = $(this).val();
        $(this).toggleClass('has-value', text_val !== "");
    }).focusout(); //trigger the focusout event manually
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.