Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string with hyphens gets evaluated as an integer (subtractions!) js

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

like image 259
sova Avatar asked Jun 02 '11 19:06

sova


3 Answers

Pass as string

dialogBody += " <a href='javascript:void(0);' onClick='class.exampleFunction(\""+ hyphenatedId +"\");'>link title</a>"; 
like image 127
amit_g Avatar answered Nov 15 '22 03:11

amit_g


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.

like image 40
Matt Avatar answered Nov 15 '22 05:11

Matt


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")
like image 27
Rob Raisch Avatar answered Nov 15 '22 04:11

Rob Raisch