Arthur  Kishinets Arthur Kishinets - 4 months ago 8
Javascript Question

Placeholder doesn`t show up

I made some jquery validation and I want some text to appear as placeholder when user went out of input and didn`t write something. I wrote this code

$('input[type="text"]').on('blur', function() {
if ( !!$(this).val() ) {
$(this).css({
'border': '#ff8383 1px solid'
});
$(this).attr('placeholder', 'this field is required');
}
else {
$(this).css({
'border': '#c3c3c3 1px solid'
});
$(this).attr('placeholder', '');
}
});


It works in chrome dev tool
chrome dev tool, but it doesn`t show up on the page.

Answer

you have an extra ! here:

 !!$(this).val()

and you can join css with attr in same (this)

$('input[type="text"]').on('blur', function() {
  if (!$(this).val()) {
    $(this).css({
      'border': '#ff8383 1px solid'
    }).attr('placeholder', 'this field is required');
  } else {
    $(this).css({
      'border': '#c3c3c3 1px solid'
    }).attr('placeholder', '');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" placeholder="test" />
<input type="text" placeholder="" />
<input type="text" />