Chris
Chris

Reputation: 185

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?

Upvotes: 1

Views: 107

Answers (3)

SURJEET SINGH Bisht
SURJEET SINGH Bisht

Reputation: 881

you missed the + operator: update this one:

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

Upvotes: 0

Jon Taylor
Jon Taylor

Reputation: 7905

Your problem is the types of quotes you are using, a mix of double and single quotes

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

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 4

Related Questions