2

I'm sorry, I still fresh with Javascript. May I know how to pass the Object variable through onClick into the function ?

The code below is my Object:

var myObject = {
    id : id,
    email : email,
    name : name,
    type : type
};

The code below I use to append:

$('#main-container').append(
    '<div>'+
    '<button onclick="passObject('+myObject+')">Submit</button>'+ //how to pass myObject here, I know I pass wrongly ps
    '</div>');

The myObject value in function is String type, Besides that, when I get value from object:

function passObject(myObject){
    console.log(myObject); // [object Object]
    console.log(myObject.email); //undefined
}
1
  • 1
    If myObject is in global scope, try just onclick="passObject(myObject)" Commented Jan 7, 2019 at 6:48

2 Answers 2

4

Attach the event listener properly using Javascript instead, so that myObject is visible through the closure, rather than using an inline handler (inline handlers are are hard to manage and are generally considered to be pretty poor practice):

function passObject(myObject){
  console.log(myObject); // [object Object]
  console.log(myObject.email); //undefined
}

const myObject = {
  id : 'id',
  email : 'email',
  name : 'name',
  type : 'type'
};

const div = $(`
  <div>
  <button>Submit</button>
  </div>
`);
div.find('button').on('click', () => passObject(myObject));
$('#main-container').append(div);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-container"></div>

Although in the code above, myObject contains strings instead of references to previous values, note that for your code, in ES6+ environments, you can use shorthand property names if you want:

const myObject = { id, email, name, type };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you, I so grateful that was helped me, and save my time.
0

big re-organise

(function() {
    var myObject = {
        id : id,
        email : email,
        name : name,
        type : type
    };

    var btn = $('<button>Submit</button>');

    btn.on( 'click', function( e) {
        e.stopPropagation(); e.preventDefault();

        console.log(myObject); // [object Object]
        console.log(myObject.email); //undefined

    });

    $('<div/>').append( btn).appendTo('#main-container');

})();

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.