Hoang Lam
Hoang Lam

Reputation: 464

Finding ID with Multiple ASP UserControl using JavaScript

I have an ASP usercontrol name ListItem. Each ListItem has 2 ASP controls on it : a label lblIndex and a button btnAction

On my page, I load 10 ListItem into a panel and set lblIndex on each ListPanel an appropriate index.

ListItem 1 : lblIndex.value = '#1'
ListItem 2 : lblIndex.value = '#2'
...
ListItem 10 : lblIndex.value = '#10'

How do I write Javascript that, each time when I click the button on a ListItem, the appropriate lblIndex's value will appear(through an Alert()). I.e. when I click the btnAction on the 2nd ListItem, the text '#2' will come out.

Thank you

Upvotes: 1

Views: 161

Answers (1)

balexandre
balexandre

Reputation: 75133

to facilitate your life, use jQuery when writing javascript.

in that in mind, let's assume that your ListItem control outputs a ul list with an id... make sure that you had a class, let's imagine that you named list-item so at the end you will have:

<div id="ListItem_1" class="list-item">
   ...
</div> 

Now, you say you some sort of a button inside that list...

<div id="ListItem_1" class="list-item>
   <input id="ListItem_1_Button_1" type="button" value="I'm a Button" />
</div> 

Once again, explicit give that button a class name, for example: inside-button

I don't know how you have all texts, but I'll again assume that will be a hiiden field with the text to alert ...

some thing like:

<div id="ListItem_1" class="list-item>
   <input id="ListItem_1_Button_1" type="button" value="I'm a Button" />
   <input id="ListItem_1_Hidden_1" type="hidden" class="text" value="Text to run" />
</div> 

and assuming you have 10 lists with several buttons you can simple write:

$(".inside-button").bind("click", function() {
    // a button was clicked, let's do something
});

that 1st line says: "Foreach DOM element that has a class name of inside-button attach the click event"

and inside you fire what you want to do

From your question, you only want to perform something on that list:

$(this)  // that will be the .inside-button element, so the Button
   .closest(".list-item")  // get me the closest DOM element with a class name of "list-item"
   .find(".text") // find the DOM elemnt with the class name "text"
   .val();  // let's see what value that element has

then you can alert() it.

All together:

$(".inside-button").bind("click", function() {
    // a button was clicked, let's do something
    var txt = $(this).closest(".list-item").find("text").val();
    alert( txt );
});

Upvotes: 2

Related Questions