简体   繁体   中英

ASP.NET Get the Ids of each control in a list of controls using javascript

in an ASP.NET/C# application, I have a list (or array) of controls (for example textboxes) declared and added in the code behind.

List<TextBox> LstOfBoxes = new List<TextBox>();

I want to use Javascript to change the visibility of all the controls in the list (or array).

I know that if i want to change the visibility of 1 textbox I use this:

document.getElementById("<%=TextBox1.ClientID %>").style.display = 'none';

But how to loop through all the list (or array), get the ids of each control and change the display to 'none'

Thanks a lot.

Obtain the list via document.getElementsByTagName() or document.getElementsByClassName() method. Another way is to wrap all input text fields (TextBox) into a <div> and set style property to that <div> .

Bear in mind that the List itself will not create an HTML element on the page. If you have a List and in your code behind you loop through that list to drop the items on the page, then you won't have any clear way to target just those textboxes. I'd wrap them in a container like so:

List<TextBox> listOfTb = MethodToFillYourList();
var panel = new Panel { CssClass = "tbHolder" };
foreach (var textbox in listOfTb)
{
     panel.Controls.Add(textbox);
}
YourControlToAddTextBoxesTo.Controls.Add(panel);

Now on the client side, hit the "tbHolder" div (Panel control = div tag in .NET) and hide each textbox inside it. Here's a jQuery and a normal JS version of that hide routine.

// New JQuery hotness
$(".tbHolder input[type=text]").hide();

// Old and Busted JS
var tbs = document.getElementsByClassName("tbHolder").getElementsByTagName("input");
for (var i = 0; i < tbs.length; i++) {
     tbs[i].style.display = 'none';
}

You sholw to store every control in repeater in div. It will helps you, when you will use jQuery selectors like parent and child. Sorry for my English :)

Assuming that you have already added the controls to the page somehow, you can simply loop through and emit a line for each function:

<script language="javascript" type="text/javascript">
function setVisibility(displayType) {
    var type = displayType || 'none';

    <% foreach (var textBox in LstOfBoxes) { %>
    document.getElementById("<%=textBox.ClientID %>").style.display = displayType;
    <% } %>
}
</script>

Since you didn't mention you were using jQuery I won't list that here, but you really should look into doing what Graham suggests .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM