mrben522 mrben522 -3 years ago 171
Javascript Question

javascript object.key not working

I have code to get GA parameters that have been stored in a cookie and make them the values of inputs in a form that isn't working and I can't for the life of me figure out why.

(function( $ ) {
if (Cookies.get('gaParams')) {
var params = Cookies.get('gaParams');
$('#source').val(params['utm_source'] ? params['utm_source'] : 'organic');
$('#medium').val(params['utm_medium'] ? params['utm_medium'] : '');
$('#campaign').val(params['utm_campaign'] ? params['utm_campaign'] : '');
$('#keywords').val(params['utm_terms'] ? params['utm_terms'] : '');



you can see it in action by going here and then clicking on the "request Quote" button.

The console.log will return
{"utm_medium":"testing","utm_source":"whatever"} undefined undefined

I don't understand why calling the object keys won't give me the values this way.

Answer Source

Because the variable params is string type . You should use this method JSON.parse() to parse a JSON string

var params = Cookies.get('gaParams');
params = JSON.parse(params);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download