Nolesh
Nolesh

Reputation: 7018

Passing parameters to jQuery function via link

I have a jQuery function:

$(function(){ 
function InitDialog(c,b){
    /* some code */     
}

$('a[name=dialog]').click(function(e)                                                 {         
            InitDialog(caption, bodyText);        
    fadeInCommon(e,this);
});
});

And also I have a link defined in html code like below:

<ul>
<li><a href="#dialog" name="someInformation" }">something</a></li>
</ul>

My question is how can I pass the parameters (caption, bodyText) to Init() function via link? I've heard about some method like below:

<li><a href="#dialog" name="someInformation" onClick="return {height: 100, width:200};"}">something</a></li> 

But I don't understand how can I get and parse it? Thanks

Upvotes: 2

Views: 11267

Answers (3)

jamie-wilson
jamie-wilson

Reputation: 1925

So first, I think you want to say $('a[href="#dialog"]') to get the a tags, then in the click function, $(this).attr("name") will give you the some information, which you could store a json string...

<a href="#dialog" name="{caption:'XXXX', bodyText:'XXXX'}">My Text</a>

$('a[href="#dialog"]').click(function() {
     var data = JSON.parse($(this).attr("name"));
     InitDialog(data.caption, data.bodyText);
});

But, I don't think that's the right way of going about what you're trying to do, would you be better to create the dialog in a div lower down the page, hide it, and only show it when you click the link? Because the term 'bodyText' implies it's going to be big...

Or just:

 <a href="javascript:InitDialog('Caption', 'BodyText'); fadeInCommon(e,this);">My Link</a>

Upvotes: 1

Jibi Abraham
Jibi Abraham

Reputation: 4696

Since you are using jquery, I would recommend that you do the following to store data on your element

<a href="#dialog" name="some_name" data-params="{'param1':'someValue', 'param2':'someOtherValue'}">Link Text</a>

Then in your click function, you can access it as shown below

$('a#dialog').click(function(){
    var me = $(this), data = me.data('params');
    //console.log(data);
});

Edit - Fiddle added

Check the fiddle to see a working sample

Upvotes: 7

widyakumara
widyakumara

Reputation: 1234

using data-* attribute, you can:

<a name='dialog'
 data-caption='this is the caption'
 data-bodytext='this is the body'>klik</a>

and the javascript:

$(function() {
    function InitDialog(c, b){
        alert('the caption: ' + c);
        alert('the body: ' + b);
        }

    $('a[name=dialog]').click(function(e) {
        caption = $(this).data('caption'); // gets data-caption attribute value
        bodyText = $(this).data('bodytext'); // gets the data-bodytext attribute value
        InitDialog(caption, bodyText);
        fadeInCommon(e,this);
        });
    });

tho instead of using name as the selector, i'd recommend class instead

Upvotes: 2

Related Questions