0

why can't i have a variable in an object? I get an error like:

"Uncaught SyntaxError: Unexpected token this"

My code is like this.

$("#search_options input:checkbox").on('click', function() {
  var params = { 
    $(this).attr('name') : $(this).val(),
  };
  var str = jQuery.param(params);
});

I'm sure that $(this) is working because I tried to console.log it outside the params object then i is working.

2 Answers 2

3

Object literals cannot have variable property names. You'll have to assign the property like so:

...
var params = {};
params[$(this).attr('name')] = $(this).val();
var str = jQuery.param(params);
Sign up to request clarification or add additional context in comments.

1 Comment

ic, didn't know that object literals can't have variables. thanks for info
2

If you want to use value of a variable as a property name, you must use this syntax:

var params = {}

params[$(this).attr('name')] = $(this).val();

The literal notation, that you're trying to use, expects property name to be a valid JavaScript identifier.

1 Comment

thanks, didn't know that i can't use variables in object literals

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.