PeMaCN PeMaCN - 5 months ago 11
jQuery Question

blur() not working if text is written to input and then erased - jQuery

I want to check if user has written something to input and then depending on that I'm adding classes

.success
or
.warning
. These classes change only border color. This is my code:

$('#myForm input').blur(function (){
if($(this).val() == '')
{
$(this).addClass('warning');
}
});

$('#myForm input').keypress(function (){
if($(this).val() != '')
{
$(this).addClass('success');
}
});


If I write some text to input it changes color to green but if I erase that text then the color is still green (and it should be red). Can anyone explain me why this happens?

Answer

It happens beacuse once you write any value the class success is added, then when you erase the content that class is still there and it's still green.

What you need is to remove and add:

$('#myForm input').blur(function (){
    if($(this).val() == '')
    {
        $(this).removeClass('success').addClass('warning');
    }
});

$('#myForm input').keypress(function (){
    if($(this).val() != '')
    {
        $(this).removeClass('warning').addClass('success');
    }
});

$('input').blur(function() {
  if ($(this).val() == '') {
 $(this).removeClass('success').addClass('warning');
  }
});
$('input').keypress(function() {
  if ($(this).val() != '') {
 $(this).removeClass('warning').addClass('success');
  }
});
:focus {
  outline: 0;
}
.warning {
  border: 2px solid purple;
}
.success {
  border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />