fumeng
fumeng

Reputation: 1830

Passing JS Object via HTML string

Having problems passing a JS object to a JS method via an HTML String. Here's a part of the HTML String:

onclick='addGrpMember("+c+"); return false;'

When I click to invoke this method I see this: Unexpected identifier

I can easily pass in properties of this c Object a la:

onclick='addGrpMember(\""+ c.contactName +"\",\""+ c.displayName +"\"); return false;'

And that works just fine.

What am I missing here? By the way, "c" is passed into the method as an arg. (where I'm executing this code).

Thanks for any helpful tips!

Updated with full code:

contact = "<tr><td style='width:60px; padding:12px 6px' title='"+ c.contactName +"'><span class='contactAvatar'><img src='<%= context %>/app/user/image?loginName="+ c.contactName +"' alt='' /></span></td><td style='padding-top:12px'><span class='contactTitle'>"+ c.displayName +"</span><br/><span class='contactTitleCompany'>"+c.title+ " at " +c.companyName+"</span><br/><a href='mailto:"+c.contactName+"'><i class='icon-envelope'></i> "+c.contactName+"</a></td><td style='padding-top:30px;padding-right:10px;text-align:right'><a href='#' data-toggle='tooltip' data-placement='right' title data-original-title='Add Member' onclick='addGrpMember("+c+"); return false;' class='addIcon'></a></td></tr>";

And the method:

   function addGrpMember( c ){
selectedGroup.members.push( c );
populateSearchResults( selectedGroup.members, 'groups' );}

Upvotes: 0

Views: 235

Answers (3)

Josh Taylor
Josh Taylor

Reputation: 532

It should work just passing in the object variable name:

<button onClick="addGrpMember(c);">Add Group Member</button>

Then in your JavaScript, something like:

var c = {
    contactName : "value1",
    displayName : "value2"
};

var addGrpMember = function (groupMember) {
    // Do something with the group member
    return false;
};

Here is a working fiddle with some similar code: http://jsfiddle.net/vgF8C/

Upvotes: 0

scottheckel
scottheckel

Reputation: 9244

You will need to convert c into a JSON string. Assuming you are making this string in JavaScript.

onclick='addGrpMember("+JSON.stringify(c)+"); return false;'

JSON.stringify is IE 8+.

With that said... there is probably a better way to do what you are trying to do, but without seeing your entire method we can't really comment on that much. Generally inline JavaScript isn't the way to go.

Upvotes: 1

Khalid
Khalid

Reputation: 4808

I think , no need to concat the string or extract the object elements, all you need is to put this code on the button event onClick

onclick='addGrpMember(c); return false;'

if c is your javascript object

Upvotes: 0

Related Questions