0

I have a jQuery with the following code:

id = 100;
name = "O'Keefe";
str = "<button type='button' onclick='selName( "+id+",\""+name+"\")'>Select</button>";

str is loaded into a div.

When I inspect the page it shows:

<button type="button" onclick="selName( 100, "O" Keefe")'>Select</button>

I tried escaping the single quote with

name = name.replace(/'/g, '\'');

But it didn't work.

My code works fine for names without single quote.

Any suggestions on how to deal with names with single quote?

Thanks.

5
  • 1
    HTML doesn't have any form of escaping inside attributes. So you simply can't have ' inside an attribute if you're using ' as the attribute value delimiter. Commented Dec 18, 2021 at 0:58
  • 1
    I tried it and everything is fine. Can you show how you are loading it into div, pls? Commented Dec 18, 2021 at 1:11
  • @Barmar Thank you. After reading your comment about escaping in HTML I did a search and found a solution - replace single quotes with &#39; It worked. :) Commented Dec 18, 2021 at 1:21
  • What has this to do with jQuery? You aren't using it to create that HTML. Commented Dec 18, 2021 at 1:38
  • 1
    You can also use backtick ` Commented Dec 18, 2021 at 2:43

2 Answers 2

1

Don't use a string for that. Since you say you're using jQuery, you should attach the event listener with jQuery, not with inline events (which have a large number of problems, including this one - tedious quote escaping).

const button = $('<button>Select</button>')
  .on('click', () => selName(id, name))
  .appendTo('selectorOfWhateverYouWantToAppendThisTo');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. I understand what you are doing, but it would require a significant change on my code. I will keep this in mind for future code. I ended up replacing the single quotes with &#39; It worked. Thanks.
0

I found a solution.

id = 100;
name = "O'Keefe";
name = name.replace(/'/g, '&#39;'); //replace single quotes
str = "<button type='button' onclick='selName("+id+",\""+name+"\")'>Select</button>";

When I replace the single quotes with &#39; the html shows:

<button type="button" onclick="selName( 100, "O'Keefe")">Select</button>

This works. Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.