user45706 user45706 - 26 days ago 9
Javascript Question

onclick function - json string variable not working

The

json
I receive looks like this:

Object:
bpi:206000
buyout:4120000
itemId:133564
itemName:"Spiced Rib Roast"
name:"Flipflap"
quantity:20
timeLeft:"VERY_LONG"
undercut:0


I'm populating a table through a jquery .each function.

One of the elements is set to fire of a function when it's pressed.

The code pushing items to the table looks like this:

$.each(data, function(i, key){
items.push('<tr class="tr1"><td><a onclick="getItemData(' + key.itemId + ',' + key.itemName')" rel="item=' + key.itemId + '"">' + key.itemName + '</a>' + "</td><td>" + getAmount(key.buyout) + "</td><td>" + key.quantity + "</td><td>" + ifUndercut(key.undercut) + "</td><td>" + key.timeLeft.replace('_', ' ') + "</td></tr>");
});


The problem is with this piece of the code:

onclick="getItemData(' + key.itemId + ',' + key.itemName')"


This piece of code gives various variation of missing syntax errors.

Swapping out
key.itemName
with another
key.itemId
makes the onclick function work.

Is it the formatting of the string that's the problem?

How can I make it work with
key.itemName
?

Answer

The issue is because itemName is a string, so you need to wrap it in quotes when it's output. You're also missing a + concatenating the string after the value. Try this:

items.push('<tr class="tr1"><td><a onclick="getItemData(' + key.itemId + ',\'' + key.itemName + '\')" rel="item=' + key.itemId + '"">' + key.itemName + '</a>' + "</td><td>" + getAmount(key.buyout) + "</td><td>" + key.quantity + "</td><td>" + ifUndercut(key.undercut) + "</td><td>" + key.timeLeft.replace('_', ' ') + "</td></tr>");

Note the addition of \' around the value.

I would also strongly suggest you research the use of both unobtrusive and delegated event handlers, as the on* event attributes are very outdated now and should be avoided where possible.