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.
CodePudding user response:
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');
CodePudding user response:
I found a solution.
id = 100;
name = "O'Keefe";
name = name.replace(/'/g, '''); //replace single quotes
str = "<button type='button' onclick='selName(" id ",\"" name "\")'>Select</button>";
When I replace the single quotes with '
the html shows:
<button type="button" onclick="selName( 100, "O'Keefe")">Select</button>
This works. Thanks.