Set CSS style for already filled fields

3

I have the following function in javascript:

 $('input').blur(function() {
  var $this = $(this);
  if ($this.val())
    $this.addClass('used');
  else
    $this.removeClass('used');
});    

It adds the class used to the element input clicked if it has value, otherwise, when it loses focus, it will not have the used class. works correctly because these fields are populated with a value that comes from the database, and since click does not occur in the input it does not add the used class, how can I to solve this?

    
asked by anonymous 22.11.2015 / 04:00

1 answer

3

When opening your HTML, check all input and add used to each one that is filled using .each() :

$(document).ready(function() {
    $("input[type='text']").each(function( index ) {
        if ($this.val())
            $this.addClass('used');
        else /* Este else é opcional. */
            $this.removeClass('used');
    });
});
    
22.11.2015 / 04:33