Search code examples
javascripthtmlanchorhref

Javascript ReferenceError while passing path


I have a javascript method

function addData(path)
{
  //logic here
}

and I am calling it as

<a id="dataSource" title="Add Data" href="javascript:addData(abc)">

This gives me error

[01:23:10.432] ReferenceError: abc is not defined @ javascript:addData(abc):1

Surprisingly it allows me to do something like

<a id="dataSource" title="Add Data" href="javascript:addData(123)">

So what should be done here ? I tried doing

<a id="dataSource" title="Add Data" href="javascript:addData('abc')">

but it gets converted to

<a id="dataSource" title="Add Data" href="javascript:addData(&apos;abc&apos;)">

and then gives me syntax error

[01:29:07.212] SyntaxError: syntax error @ javascript:addData(&apos;abc&apos;):1

Using onclick instead of href also has same effect.

I want to pass a path to the method which would be something like /package/version/1.0/data


Solution

  • You should be attaching a click handler or, if you must, use the onclick attribute to call JS functions.

    <a id="dataSource" title="Add Data" href="javascript:addData(abc)">
    

    Doesn't work because abc is a variable. It obviously doesn't exist from there.

    <a id="dataSource" title="Add Data" href="javascript:addData(123)">
    

    This works because 123 is an integer(number) literal.

    <a id="dataSource" title="Add Data" href="javascript:addData('abc')">
    

    This string is getting encoded automatically for security reasons. You would need to escape a string literal if you had to pass it in this way. I find I don't need to do anything with onclick and this would work just fine. See here: http://plnkr.co/edit/s5Mxz8KPYcUypEkY0qdX?p=preview

    This should work just fine:

    <button id="dataSource" onclick="addData('abc')">Add</button>
    

    Hopefully that helps.