5

I have the following initialized object, and I want to pass this object through onclick function, is this possible to achieve?

var nameObject = { Name: "Stack", lastName:"Exchange" }

Here is my code:

In the document ready I have link with onclick function that is append into html element.

Html:

<div id="test"></div>

Javascript:

$(document).ready(function () {
  var nameObject = { Name: "Stack", lastName:"Exchange" };

  $("#test").append('<a href="#"'
  +'onclick="sendObj(**I want to pass "nameObject" into this function)">'
  +'sendObject</a>');
)};

function sendObj(**receive the object**)
{
  //nameObject.Name+" "nameObject.lastName;
}

Jsfiddle

3
  • What do you mean by "sending"?? nameObject and sendObj are within the same scope so the sendObj function has access to the nameObject variable. Commented Sep 14, 2013 at 18:56
  • What are you trying to achieve? What is not working in your fiddle? Commented Sep 14, 2013 at 18:56
  • this is not working -> jsfiddle.net/C6ghj/10 Commented Sep 14, 2013 at 19:00

2 Answers 2

4

try this

$(document).ready(function () {
  var nameObject = { Name: "Stack", lastName:"Exchange" };

  $("#test").append('<a href="#" data-caller>sendObject</a>');

  $("#test").on("click", "[data-caller]", function() {
     sendObj(nameObject);
  });
)};

function sendObj(nameObject)
{
  alert(nameObject.Name+" "+nameObject.lastName);
}

working jsfiddle

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

Comments

4

A more appropriate way of doing what you want is to store the object in the element's data object, which is what jQuery designates for this very purpose.

Then, assign a click handler that would call your desired function with the stored data.

$(document).ready(function () {
    var name = { Name: "Stack", lastName:"Exchange" };
    var a =  $('<a href="#">sendObject</a>').data('name', name).on('click',
       function(e){
           sendObj($(this).data('name'));
       });

    $("#test").append(a);
 });

function sendObj(e)
{
    console.log(e);
}

Demo (say hello to console, ditch alert()).

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.