1

I have this in my html...

<button onclick="myFunction(array['foo':['bar', 'pub']])">Click Me</button>

However, the browser complains, "SyntaxError: missing ] in index expression".

I've checked for missing brackets and am pretty sure it's all good, as well as making sure the receiving function worked (switched out original for one that just prented the array to test with.)

1
  • 1
    UM, you should be using an object. Commented Oct 29, 2015 at 21:07

2 Answers 2

3

String-associative objects are called, just as hinted, Objects. Arrays are a specific type of object that access their elements by numerical index. Objects also use a different literal syntax, and neither uses a keyword to instantiate them.

<button onclick="myFunction({'foo':['bar', 'pub']})">Click Me</button>

That said, have you looked into "data-... attributes"?

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Sign up to request clarification or add additional context in comments.

2 Comments

Too much switching between languages, forgot the brackets, thanks. :P As for data attributes, doesn't really work for my end goal. (The variables for the function aren't altered on the page, but the function will be reused with variations on lots of different pages... unless there's some functionality of data attributes I'm missing?)
Here's how I would do it. <button class="canBeClicked" data-foo="bar" data-fi="pub">, along with some JavaScript on each page that queries for the canBeClicked class, and adds a click listener that checks those data attributes and acts accordingly. Now you are not tied to the onclick attribute, you don't need your function to be a global, and your users won't get an error when they click your button before the JS loads.
1

I am not sure where you picked up that syntax, but it is not right. You should be using an object.

myFunction({'foo':['bar', 'pub']})

Comments

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.