thisissami
thisissami

Reputation: 16343

How do I use JQuery to create an onclick javascript link in HTML with quote-including-string parameters?

I'm trying to create a link as follows in HTML:

<a href="javascript:void(0) onclick="print(string)">

I'm doing this using JQuery as follows:

html = '<a href="javascript:void(0)" onclick="print(\'' + string + '\')">'

However, I run into problems when string itself contains a single quotation mark. Is there any way that I can do something of this sort regardless of the characters contained in string? The main ones I'm trying to figure out are both single and double quotation marks.

Best, and thanks for any advice,
Sami

Upvotes: 0

Views: 116

Answers (3)

Cameron Chapman
Cameron Chapman

Reputation: 796

Since your using jQuery why not use the event listeners it provides?

Give your link an id value:

<a href="#" id="someID">anchor</a>

Define the desired behavior with jQuery:

$('#someID').click(function(e) {
    e.preventDefault();// prevent the default anchor behavior
    $('#someID').text('New anchor text');// this is an example of the functionality
});

An example: http://jsfiddle.net/BfHrW/

Upvotes: 0

Michael Zaporozhets
Michael Zaporozhets

Reputation: 24526

You could do this quite easily by simply encoding the string as a URIComponent before placing it in and then decoding it when you need it.

ie.

var NoQuotesString = encodeURIComponent(string);
//to encode the string without quotes

var BringBackMyQuotes = decodeURIComponent(NoQuotesString);
//decodes the string back to the original

Upvotes: 1

Tulio
Tulio

Reputation: 955

I'm not sure if I understood your problem, but have you already tried the escape function?

Like this:

html = '<a href="javascript:void(0)" onclick="print(\'' + escape(string) + '\')">'

Upvotes: 1

Related Questions