Reputation: 23
I have this button with an onclick attribute which calls a function named appr
. The parameters passed to appr
are different for each button, generated by PHP:
return "<button type='button' onclick='appr(".$id.",\"".$qr['name']."\");'>Approve</button>";
Which results in this HTML:
<button type='button' onclick='appr(3,"Dave O'Shea");'>Approve</button>
The Javascript function look like this.
function appr(id,name){
// some code here...
alert(name);
}
The code works fine, except for strings with single quotes, which fails. Any ideas why?
Upvotes: 0
Views: 2572
Reputation: 99
Best solution is to use template literals and escape function for dynamic data in attributes. Like following example
let str = escape("Dave O'Shea")
return `<a href="javascript:void(0);" onclick="myFunc(str)"></a>`
then in function unescape the string
function myFunc(str){
str = unescape(str)
}
Upvotes: 0
Reputation: 370689
In your code, single quotes denote the attribute boundaries:
onclick='appr(
^
so the first '
that comes afterwards will finish the attribute value.
You can fix it by replacing the '
s with HTML entities that result in quote marks instead, so that the generated HTML comes out to
<button type='button' onclick='appr(3,"Dave O"Shea");'>Approve</button>
<button onclick='alert("foo")'>Test</button>
But it would be far better to avoid inline handlers entirely and add the listeners with Javascript instead. For example, for each button, push an object containing the associated id
and name
to an array, and include that array in the response to the client somehow - for example, by putting the JSON into a script tag and selecting / parsing that script tag content. Then iterate over the array and add a listener to each button. Something like:
// retrieve array however you want
const arr = [
{ id: 3, name: "Dave O'Shea" },
// more objects
];
const buttons = document.querySelectorAll('button');
for (const [i, { id, name }] of arr.entries()) {
button[i].addEventListener('click', () => {
appr(id, name);
});
}
Or anything else along those lines. Just avoid putting handlers in the HTML markup as element attributes.
Upvotes: 1