Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

Couldn't append variable with single quote to anchor tag's title

I am getting data from database that has single quotes in it. There are no problems in getting that, I get variable with single quotes in it

ex:

var title="vicky's blog";

Now the problem is I am not able to append this variable as title for anchor tag.

I have tried using escape, unescape, replacing with regex and all that. I think i am missing out something, please help.

http://jsfiddle.net/vigneshvdm/mtXSZ/

Please refer to this jsfiddle. Inspect the anchor tag there its not having the full variable as title.

I also tried solutions provided in

Using JavaScript single and double quotes for href's

jQuery single quote in JSON response

Upvotes: 0

Views: 3312

Answers (4)

Nagarajan A
Nagarajan A

Reputation: 89

See this i think it will help you: enter image description here

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173642

Just create the anchor with jQuery and let it solve the escaping issue:

var $anchor = $('<a>', {
    href: '#',
    title: title,
    text: 'hello'
});
$('#testing').html($anchor);

Demo

Upvotes: 2

Musa
Musa

Reputation: 97707

If you want to put text in html you should always html encode the special characters.

'"<>&

var title="vicky&apos;s blog";

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

You need to wrap the title value inside "" in the html element

$("#testing").html('<a href="#" title="'+unescape(title)+'">hello</a>');

Demo: Fiddle

But I would recommend

var title="vicky's blog's test dd \" with";

$('<a />', {
    href: '#', 
    title: title,
    html: 'test'
}).appendTo('#testing')

Demo: Fiddle

Upvotes: 4

Related Questions