charan
charan

Reputation: 292

passing parameters in anchor tag onclick event

I'm creating anchor tag dynamically like

for (var i = 0; i < json.length; i++)
{
      <td><a href='#'  id=" + json[i].id + " onclick=getId('" + json[i].id + "','"+ json[i].text +"')>" + json[i].text + " </a></td>
}

and In the onclick function I have defined like

function getId(ID,text)
{
      console.log(ID);
      console.log(text);
}

In this onclick event If the text value doesn't contain any space or gap between word to word, I'm able to get the text value in console, In-case If text contains any spaces then It is showing error like Unexpected token ILLEGAL.

Upvotes: 2

Views: 5426

Answers (2)

Calvin
Calvin

Reputation: 1295

It is possible that your text value could have an invisible character that causes the Unexpected token ILLEGAL.

No visible cause for "Unexpected token ILLEGAL" should explain more on ILLEGAL characters.

Remove zero-width space characters from a JavaScript string could help you try to remove these characters.

Upvotes: 0

Satpal
Satpal

Reputation: 133403

<a href='#' id=" + json[i].id + " onclick=getId('" + json[i].id + "','"+ json[i].text +"')>" + json[i].text + " </a>

Above code might work, but IMHO its not good practice.

Try this, I prefere it this way and much cleaner.

var a = document.createElement('a');
a.setAttribute('id',json[i].id);
a.setAttribute('href',"#");
a.innerHTML = json[i].text;
a.onclick = function(e) {
    getId(json[i].id, json[i].text);
    e = e || window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    return false;
};

Upvotes: 1

Related Questions