ToTa
ToTa

Reputation: 3334

Pass initialized object to javascript function

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

Upvotes: 5

Views: 1606

Answers (2)

MasterAM
MasterAM

Reputation: 16478

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()).

Upvotes: 4

Milad Hosseinpanahi
Milad Hosseinpanahi

Reputation: 1495

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

Upvotes: 4

Related Questions