Axiol
Axiol

Reputation: 5962

Remove quote from a jQuery variable

So I'm making an Ajax request in a Rails app and I hava a little problem when I want to recover variable.

Let say that the data I pass to the Ajax request looks like this

var dataAll = ({dataForKey: dataItemID});

And let say that the two seconds variable are recovered like this

var dataForKey = '<%= feed_item.class.to_s.foreign_key %>';
var dataItemID = '<%= feed_item.id %>';

Imagine that feed_item.class.to_s.foreign_key returns photo. So, dataForKey value's is 'photo'.

But, I need dataForKey to be photo and not 'photo' and I can't say

var dataForKey = <%= feed_item.class.to_s.foreign_key %>;

Because jQuery looks for a variable called photo...

So, let's summarize it : how can I remove the quote from dataForKey ?

Upvotes: 0

Views: 441

Answers (3)

Anthony Grist
Anthony Grist

Reputation: 38345

Rather than saving the name of the key into a variable, just output it directly:

var dataItemID = '<%= feed_item.id %>';
var dataAll = ({<%= feed_item.class.to_s.foreign_key %>: dataItemID});

Or, create your object and set the values separately:

var dataForKey = '<%= feed_item.class.to_s.foreign_key %>';
var dataItemID = '<%= feed_item.id %>';
var dataAll = {};
dataAll[dataForKey] = dataItemID;

Upvotes: 2

Eric
Eric

Reputation: 10658

dataForKey = dataForKey.replace("'", "");

Upvotes: 0

knabar
knabar

Reputation: 1156

You can try and use eval:

var dataForKey = eval('<%= feed_item.class.to_s.foreign_key %>');

Upvotes: 0

Related Questions