0

Solved, server side ate my {}.

I have this code in my HTML:

onclick="changes = {'a': 'b'};"

This transforms to

onclick="changes = ;"

when I load the page. So the curly braces and everything in between disappears. Any idea how to fix this? Ultimately, I want to give an anonymous object as input to a function:

onclick="dothis({'a': 'b', '1': '2'});"
user773085
  • 31
  • 5

2 Answers2

4

What I would recommend is making your code more semantic, by having your inputs keep track of data, but the actual binding and execution separate:

<div id="myDiv" data-changes="{'a':'b', '1':'2'}"></div>


document.getElementById('myDiv').onclick = function() {
    var data = JSON.parse(this.getAttribute('data-changes'));

    // here you should be able to say data.a, data.1, etc.
};

Most modern browsers support native JSON methods:

Browser-native JSON support (window.JSON)

but for those that don't, you can add support with the JSON library:

https://github.com/douglascrockford/JSON-js

Community
  • 1
  • 1
Eli
  • 17,397
  • 4
  • 36
  • 49
0

Have you considered/are you able to not use inline JavaScript? Just have an external JavaScript file that gets loaded with something like (not actual code, for example purposes):

getElementById("myButton").click( function(){
   dothis({'a':'b','1':'2'})
})

Something like that (especially when paired with a library) can also save you from having to duplicate your code in every item you're looking to run that function in.

Shauna
  • 9,495
  • 2
  • 37
  • 54
  • Please take into account that the example given is pseudo-code, not something that actually works. – kapa May 27 '11 at 13:05