Search code examples
jqueryinputdetect

detect input value length on focus


When the user start to type inside of the input I would like the input to do something, so I have tried to write it like this:

$('input').focus(function(){
  if ( $('input').val().length > 0 ) {
    $('input').css('color', 'red');
  }
  else {
    $('input').css('color', 'blue');
  }
});

Just to get the Idea how to detect when the input isn't empty
What am I doing wrong?


Solution

  • Try this Demo here

    $('input').keyup(function(){
      if ( $(this).val().length > 0 ) {
        $(this).css('color', 'blue');
      }
      else {
        $(this).css('color', 'red');
      }
    });