jkupczak
jkupczak

Reputation: 3031

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 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.

Upvotes: 0

Views: 2226

Answers (2)

roselan
roselan

Reputation: 3775

you can do it on "page load"

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

Upvotes: 2

Adam Fabicki
Adam Fabicki

Reputation: 530

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/

Upvotes: 0

Related Questions