-3
<script>

var id = "432.000+444";
myFunc(id);
document.write("<a onclick=\"myFunc("+id+");\" href=#>Click me</a><br>");

function myFunc(id) {
    alert(id);
}

</script>

myFunc(id) prints the string normally, but clicking on the element prints 876 (treats it as a number and adds 432 and 444). How can I prevent this? I want it to always be treated as a string.

Kidades
  • 600
  • 2
  • 9
  • 26
  • 2
    This wouldn't be an issue if you wrote saner Javascript, e.g. `document.getElementById('myLink').addEventListener('click', myFunc.bind(null, id))`; `document.write`ing concatenated Javascript literals is pretty bad practice… – deceze Aug 18 '17 at 14:07

2 Answers2

3

Put it in quotes:

document.write("<a onclick=\"myFunc('"+id+"');\" href=#>Click me</a><br>");
// ---------------------------------^------^

FWIW, I strongly advise not using onxyz-attribute-style event handlers. For one thing, the functions you call from them have to be globals, which is generally not a good thing. Instead, use modern event handling (addEventListener, or attachEvent on old IE; here's a function that handles that issue) or at least the onclick property.

var id = "432.000+444";
var link = document.createElement("a");
link.onclick = myFunc.bind(link, id);
link.href = "#";
link.appendTextNode("Click me");
appropriateParentElement.appendChild(link);
appropriateParentElement.appendChild(document.createElement("br"));

function myFunc(id) {
    alert(id);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks, that worked. I tried to put it under double quotes, but it didn't work for some reason. Looks like I needed single quotes instead. – Kidades Aug 18 '17 at 14:10
  • @Kidades: This is another of the many reasons not to use `onclick`-attribute-style handlers: Double quotes weren't working for you because the content of a double-quote-delimited attribute cannot contain a literal double quote. (Attribute values are HTML text, you could use `&quote;`, but it makes for really hard-to-read JavaScript.) – T.J. Crowder Aug 18 '17 at 14:15
  • Double quotes can work, but you'd have to escape both the double quote and the preceding `\\ `. It'd be a mess. Much more readable and far less error-prone to just use single quotes. –  Aug 18 '17 at 14:31
  • @Amy: No, ``\`` isn't for escaping in HTML text. – T.J. Crowder Aug 18 '17 at 14:33
2

You need to wrap it in quotes.

                                    ↓      ↓
document.write("<a onclick=\"myFunc('"+id+"');\" href=#>Click me</a><br>");

Notice the single quotes.