I am trying to pass a value like "108-17-014" to a function through onClick...
hyphenatedId = "107-17-14"
dialogBody += " <a href='javascript:void(0);' onClick='class.exampleFunction("+ hyphenatedId +");'>link title</a>";
And inside class.exampleFunction,
exampleFunction : function ( hyphenatedId ) {
console.log(hyphenatedId);
}
However, when I click the link, the console.log does not show "107-17-14" but instead shows 76 ... because it is interpreting the hyphens as subtraction operators.
How do I prevent this from happening? Any other suggestions are welcome =)
Pass as string
dialogBody += " <a href='javascript:void(0);' onClick='class.exampleFunction(\""+ hyphenatedId +"\");'>link title</a>";
You are dynamically creating the text in the onClick at runtime, so what you end up getting looks like this:
<a href='javascript:void(0);' onClick='class.exampleFunction(107-17-14);'>link title</a>
You can see, then, why the values are getting subtracted first - there is nothing to indicate in the above JavaScript that it is actually a string. All you need to do is wrap the arguments in quotes:
dialogBody += " <a href='javascript:void(0);' onClick='class.exampleFunction(\""+ hyphenatedId +"\");'>link title</a>";
Note you have to escape the quote, otherwise it will treat it as a termination point of your string construction.
As the previous poster noted, if id="3-2-1" then:
'f('+id+')'
evaluates to the string:
'f(3-2-1)'
that then evaluates to:
f(0)
when what you wanted was:
'f("3-2-1")'
which should have started as:
'f("'+id+'")'
evaluating to:
f("3-2-1")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With