I have a setup, something confusing like this:
<ListView>
<ItemTemplate>
<div id="Content">
<asp: TextBox ID="OuterTextBox" />
<div id="Controls">
<asp: ComboBox ID="InnerComboBox"/>
</div>
<div>
<asp: Button ID="Submit" />
</div>
</div>
</ItemTemplate>
<ListView>
Wonky I know, this is just a mockup. The real thing is worse. This is an ItemTemplate so this is obviously going to dynamically generate IDs when the page is compiled. What I’m trying to do is use jquery to create an object that starts at the level of the div labeled “Content”, then search all of it’s children (recursively) to find the value of each specified control. In this example, they are OuterTextBox and InnerComboBox. What is confusing me is the ridiculous hierarchy of elements. How do I do this the most efficiently? I can only assume that shortly down the road, there will be changes to the hierarchy of divs, so I’m hoping to get something that won’t break as soon as I move something, so explicit paths to the controls aren’t going to work. Here is the concept I’m currently trying to expand on:
function ClientIDS(obj) {
var txt = $(obj).prevAll('input[id*="txtTextBox"]:first');
alert($(txt).val());
return false;
}
I would then do something like OnClientClick=”ClientIDS(this)” in the server control.
This code is simple and clean, and worked perfectly when all of the controls were in the same div (as siblings). Can anyone come up with a way to find the controls in a similar, simple fashion to this when the controls get broken up by divs like this?
The usual way you find other items in the same container as you, but not necessarily siblings is to use
.closest()to find the desired common ancestor constainer and then use.find()to find the actual element you’re looking for in that container using class names.I’m not sure exactly where your click starts, but lets say you had multiple items that came from this itemTemplate that I’ve modified to have a few classes:
Then, from the submit button, you could use:
And that would give you the textbox that was in the same container as the button that was clicked on.