user773085
user773085

Reputation: 31

javascript, curly brace in onclick dont work?

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'});"

Upvotes: 0

Views: 864

Answers (2)

Eli
Eli

Reputation: 17825

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

Upvotes: 4

Shauna
Shauna

Reputation: 9596

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.

Upvotes: 0

Related Questions