5

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 =)

sova
  • 5,468
  • 10
  • 40
  • 48

3 Answers3

7

Pass as string

dialogBody += " <a href='javascript:void(0);' onClick='class.exampleFunction(\""+ hyphenatedId +"\");'>link title</a>"; 
amit_g
  • 30,880
  • 8
  • 61
  • 118
2

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.

Matt
  • 41,216
  • 30
  • 109
  • 147
2

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")
Rob Raisch
  • 17,040
  • 4
  • 48
  • 58
  • very insightful. I appreciate the reduction, since it's much easier to see with less characters around =D – sova Jun 02 '11 at 19:52