How can I pass an object value name to a function in Jquery

1.9k views Asked by At

I'm working with the JQuery Simple modal plugin and I would like to pass a Freemarker variable/object on the click of a link to my Jquery function.

As a test, I created an alert box to see if the value is being passed and it doesn't seem to work.

$(function() {

    // Load dialog on page load
    //$('#basic-modal-content').modal();

    // Load dialog on click
    $('#hey').click(function myName(uid) {
        var x = uid;
        alert(uid);

        return false;
    });
});

HTML

<div id="disclaimer${item.uid}">
    Modal data
</div>

<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>

The alert box just comes up as a blank object. Any help would be appreciated. Thanks!

2

There are 2 answers

1
mnickell On

try using this:

function myName(uid){
  alert(uid);
}

You dont need to wrap it in a jquery event handler, because you are already calling it as an onclick event from your Freemarker template.

Alternatively, you could do something like this:

<a data-uid="${item.uid}" id="hey">...</a>

And have your javascript like this:

$('#hey').click(function(){
  alert($(this).data('uid'));
}
1
nurdyguy On

First off, you look like you are confusing the html onclick attribute with the jquery .click method.

    <a onclick="myName('${item.uid}')" id="hey">Read the blog</a>

This will call a javascript function named "myName" and pass it a the string ${item.uid}. Note, this is a string because you wrapped it in single quotes. If you do an alert, your alert will literally say "${item.uid}".

Then you have a jquery bind event for click:

    $('#hey').click({....

Ok, you need to pick one. Either use the onclick to call a javascript function or use the bind click event. Both methods can work (I prefer javascript onclick functions myself but that is just opinion).

If you want to use the jQuery bind, put a debugger; line in it so that you can step through it easily and watch. I typically use e for my event variable and e.target gets the target of the event. It will look something like this:

    $('#hey').click(function(e){
      debugger;
      alert($(e.target).attr('data-uid'));
    });

--- edit--- Adding my note below here so it is easier to read.

One thing I like to do in my onclick functions is to pass the this pointer. This is especially useful if you have multiple of the same kind of node that are calling the same function.

    <a onclick="myName(this)" id="hey2">Read the blog</a> 
    <a onclick="myName(this)" id="hey3">Read the blog</a>

then, in the javascript you function looks like:

    function myName(ptr) 
    {
        $(ptr).....
        // do some stuff 

    }