-1

Is this possible to pass an Object to a javascript when it is created from a string ?

I tried this, but it don't look to work :

var myobject = {name:"auto",color:"blue"};

var btn = "<button type='button' onclick='myfunc(" + myobject + ");'>Edit</button>";

If I inspect the onclick event, the object look like : [object Object]

2
  • You can do this, but you would need to encode it to be a string. You can use JSON.stringify() for this. And then, you would need to escape for HTML (or set the attribute value directly). Really though, don't do what you're doing. Add an appropriate event handler and make this much easier on yourself. Also consider using data-* attributes if data on the element is more appropriate, and then you can assign a single click handler for all your buttons. Commented Jun 16, 2014 at 15:12
  • Rule of thumb: when working in JavaScript, prefer DOM manipulation over string manipulation. Commented Jun 16, 2014 at 15:18

2 Answers 2

1

Maybe it's possible, but it's very wrong practice.

Better is, using second function:

var myobject = {name: "auto", color: "blue"},
    btn = "<button type='button' onclick='myfunc2()'>Edit</button>",
    myfunc = function(obj) {
        // some function
    },
    myfunc2 = function() {
        myfunc(myobject);
    };

Using JSON object format make your app open for any injections. So, try to refactor your code. And make sure, that you really need it.

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

Comments

-1

you could stringify the object like :

"(" + JSON.stringify(myobject) + ")"

i wonder why you do not simply

 onclick='myfunc(myobject);'

if myobject variable is set at the moment you click it will suit

1 Comment

This is not enough. Data would also need to be escaped for HTML.

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.