0

I have this code where I grab an attribute value and load it into a form, the headline line can look something like:

Welcome to America's best valued whatever

But when using this escape function, the string is cut off at the apostrophe,

var headline = escape($(this).attr("data-headline"));

//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(headline);

I've also tried using the solutions here: HtmlSpecialChars equivalent in Javascript? with no luck.

How can I populate my input and keep apostrophe's/quotes?

Community
  • 1
  • 1
  • You can just use `$('input[name="headline"]', e.currentTarget)` to select vs select and find. Why do you need to escape it in the javascript? Just setting the value shouldnt cause any issues. – Marie Feb 16 '17 at 15:33
  • What's the point of calling `escape` here? a) [it does not do](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape) what you think it does b) there's no need to escape a string that goes into `.val()`! – Bergi Feb 16 '17 at 15:33
  • `escape` seems to be deprecated and mostly used for `URIs` rather than for escaping apostrophes – Kaddath Feb 16 '17 at 15:34
  • `escape` is long time deprecated and should not be used for what you try to achieve. I'm sure jQuery has another function which you can use. – Nico Van Belle Feb 16 '17 at 15:36
  • Why is my string being cut off at the apostrophe when populated into .val()? @Bergi – handlethisman Feb 16 '17 at 15:36
  • @handlethisman Have you tried `console.log($(this).attr("data-headline"))` to check what your string actually is? – Bergi Feb 16 '17 at 15:38
  • The problem is probably when you was setting the attribute at the first place. Take a look at the element, it's probably looks like this: `` which then the value of the attribute will be `Welcome to America` and the rest will be regarded as attributes themselves `` – ibrahim mahrir Feb 16 '17 at 15:44

2 Answers2

0

Just use

$(this).find('input[name="headline"]').val(this.dataset.headline);

No need for any escaping.

However, notice that escape does not cut off apostrophes, it replaces them with %27. If your current code does not work with apostrophes in the headline, make sure that the markup containing the data-headline attribute is properly escaped by whatever tool is creating it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-2
var headline = $(this).attr("data-headline").replace(/'/g, '%27');
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(unescape(headline));

If browser compatibility is important, dataset is only available IE11+ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#Browser_compatibility