How to change placeholder with Font-Awesome content using jQuery?

I want to change the placeholder attribute trying to attr()use it like this:

$(this).attr("placeholder", " Mandatory field");

But the result is not a Font-Awesome icon, it literally looks like this:

" Mandatory field"

However, if I put

<input type="text" class="mandatory_field form-control" id="affiliation" placeholder="&#xf0a4; Mandatory field"/>

with CSS

.mandatory_field {  
   font-family: FontAwesome,"Helvetica Neue",Helvetica,Arial,sans-serif; 
}

This works, but I need to know how to get these results dynamically using jQuery.

Thanks in advance.

+6
source share
2 answers

This solution needs only:

  • single line jQuery
  • CSS property font-family:FontAwesome
  • No HTML at all

CSS \u. . . , , . jQuery:

$('.mandatory_field').attr('placeholder', '\uf0a4 Mandatory field');

CSS JavaScript - u JavaScript.

::placeholder . , .

Demo

$('.mandatory_field').attr('placeholder', '\uf0a4 Mandatory field');
/* With the exception of font-family:FontAwesome everything
|| is optional.
*/

input {
  font: inherit
}

.mandatory_field::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}

.mandatory_field::-moz-placeholder {
  /* Firefox 19+ */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}

.mandatory_field:-ms-input-placeholder {
  /* IE 10+ */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}

.mandatory_field:-moz-placeholder {
  /* Firefox 18- */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css">

<input type="text" class="mandatory_field form-control" id="affiliation">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hide result
+4

data $input.data('placeholder') + ' Mandatory field'.

:

var $input = $('#affiliation'),
    placeholder =  $input.data('placeholder') + ' Mandatory field';
    
$input.attr('placeholder', placeholder);
.mandatory_field {  
  font-family: FontAwesome,"Helvetica Neue",Helvetica,Arial,sans-serif; 
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" data-placeholder="&#xf0a4;" class="mandatory_field form-control" id="affiliation">
Hide result
+3

All Articles