user1027167
user1027167

Reputation: 4438

'tag' field jQuery

I am creating a popup menu with jQuery with some buttons. Number of buttons is flexibel. For each item in the variable 'items' there is one button. The problem: If the button is clicked I want to know to which item it belongs to.

In other programming languages there is a so called 'tag'-field where you can put an integer or an object for identification. What is the best way in jQuery?

var popup = $('<div />');
for (var i = 0; i < items.length; i++)
{
    var btn = $('<div>' + items.Name + '</div>').appendTo(popup).button().click(
        function(e) {
            // alert($(e.target).tag);
            popup.hide();
        }
    );
    // btn.tag = i;
}

Upvotes: 2

Views: 188

Answers (2)

detaylor
detaylor

Reputation: 7280

Try looking at .data(). This will allow you to store information associated with a key for any element.

var popup = $('<div />');
for (var i = 0; i < items.length; i++)
{
    var btn = $('<div>' + items.Name + '</div>').appendTo(popup).button().click(
        function(e) {
            // alert($(e.target).tag);
            popup.hide();
        }
    );
    btn.data("index", i);
}

You can the retrieve the information using btn.data("index") where btn is a jQuery object containing the element.

Update - Accessing the element that has been clicked within a function

The this keyword will refer to the html element that has been clicked. You could alert the stored data using:

function(e){
   alert($(this).data("index"));
}

Upvotes: 2

Steve
Steve

Reputation: 2997

You can use the "data-" attribute...

var popup = $('<div />');
for (var i = 0; i < items.length; i++)
{
    var btn = $('<div ' + 'data-tag="' + i + '">' + items.Name + '</div>').appendTo(popup).button().click(
        function(e) {
            // alert($(e.target).tag);
            alert($(this).data("tag"));
            popup.hide();
        }
    );
    // btn.tag = i;
}

Upvotes: 2

Related Questions