开发者

jQuery: Add a class to an input when a value is already entered when the page is loaded

I'm using the follow jQuery code to style some inputs based on whether they are focused or if they have content in them.

$('.Textbox')
.focus(function() { $(this).addClass("selected") })
.blur(function() { if ($(this)[0].value == '') { $(this).removeClass("selected") } });

My 开发者_Go百科problem is that some of my inputs are automatically filled in by the browser if the user is a returning visitor. Like username and password fields for example. Since the inputs have a value entered in them, I want to style them differently. Unfortunately the jQuery won't apply the styles until the user interacts with the input directly.

Is there any way that I can look to see if the input has a value (without the user interacting with the input) and then give it a class name?

Any help would be greatly appreciated.


you can do it on "page load"

$(document).ready( function () {
    $('.Textbox').each( function () {
        $this = $(this);
        if ( this.value != '' ) $this.addClass('yourClass');        
    });
});


the focus() and blur() events are specific to user interaction. You should try the change() event in jQuery, as that gets fired when the value of an input changes, even if that change was triggered by a program and not just the user: http://api.jquery.com/change/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜