You Old Fool
You Old Fool

Reputation: 22941

Add html entity by name with jQuery prop()

I'd like to add an ellipsis to an input element's placeholder attribute with jQuery prop() but instead of the intended I get literal string ….

How can I add html entities by name with jQuery prop()?

$(document).ready(function(){
	$('div#b input').prop('placeholder','Search…');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="a"><input type="text" placeholder="Search&hellip;" /></div><br />
<div id="b"><input type="text" /></div>

Upvotes: 3

Views: 993

Answers (3)

Robert McKee
Robert McKee

Reputation: 21487

Just type a horizontal ellipsis:

$(document).ready(function(){
	$('div#b input').prop('placeholder',$(document.createElement('div')).html('Search&hellip;').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="a"><input type="text" placeholder="Search&hellip;" /></div><br />
<div id="b"><input type="text" /></div>

Upvotes: -1

Felix Kling
Felix Kling

Reputation: 816364

You have to invoke the HTML parser one way or the other. You could create a new element, set its HTML content and get its content as text:

$('div#b input').prop(
  'placeholder',
  $('<div />').html('Search&hellip;').text()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b">
  <input />
</div>

See HTML Entity Decode

Upvotes: 1

Evan Davis
Evan Davis

Reputation: 36592

The simplest solution is to use the raw hex code instead of the named entity, as these are handled just fine by JS and the DOM API.

$(document).ready(function(){
	$('div#b input').prop('placeholder','Search\u2026'); // <- \u2026 is &hellip;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="a"><input type="text" placeholder="Search&hellip;" /></div><br />
<div id="b"><input type="text" /></div>

Upvotes: 3

Related Questions