最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery Check if input is empty on page load - Stack Overflow

programmeradmin1浏览0评论

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 es 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:

JSFiddle: /

Cheers!

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 es 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:

JSFiddle: http://jsfiddle/16g7yhLf/

Cheers!

Share Improve this question asked Feb 6, 2015 at 13:48 MattMatt 4266 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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
});
发布评论

评论列表(0)

  1. 暂无评论