Enable/Disable All Buttons in a GridView using JavaScript
Sometimes you might find yourself in a situation where you have a GridView that has a number of buttons that you need to enable or disable all at once and don't want to have to force a post back on your users in order to loop through them all. Thankfully with a little client side magic (JavaScript), it's very easy to do just that.
When a GridView renders on the page, it is simply an HTML table (if you don't believe me, view the source of a page with a GridView yourself) and you can traverse it just like you would any other HTML table using JavaScript.
Below is code to do a basic version of this in order to enable or disable all buttons in a GridView. First the code gets an instance of the GridView using the ClientID of the GridView (to avoid ID mangling) then create a collection of all input controls in the GridView. Next it loops through each input control and checks the type (this is necessary because input controls include not only submit buttons but also things like textboxes). Finally we either enable or disable the submit button.
<script type="text/javascript" language="javascript">
function disableAllButtons()
{
var gridViewID = "<%=gvTest.ClientID %>";
var gridView = document.getElementById(gridViewID);
var gridViewControls = gridView.getElementsByTagName("input");
for (i = 0; i < gridViewControls.length; i++)
{
// if this input type is button, disable
if (gridViewControls[i].type == "submit")
{
gridViewControls[i].disabled = true;
}
}
}
function enableAllButtons() {
var gridViewID = "<%=gvTest.ClientID %>";
var gridView = document.getElementById(gridViewID);
var gridViewControls = gridView.getElementsByTagName("input");
for (i = 0; i < gridViewControls.length; i++) {
// if this input type is button, disable
if (gridViewControls[i].type == "submit")
{
gridViewControls[i].disabled = false;
}
}
}
</script>
By changing the value in the getElementsByTagName, it is easy to get things like all the dropdown boxes in a GridView. You can even grab TR and TD elements and walk through each cell of your GridView. I just showed you a very basic example of this, but with a little fine-tuning you can control most any aspect of your GridView.
I found this particular code useful to include along with the AJAX Animation Control Extender. OnLoading of pages, I can disable all controls on the page to prevent users from clicking something before the page is ready or while a save is occurring and then use the OnLoad event to re-enable all the buttons.
I haven’t verified this to be sure, but I believe you can port this code over exactly for DataGrids and probably any other Grid or List control. As long as they render as HTML tables (DataGrids do for sure), it should work.
Click here for a demo of this code in action. This code is simply using a GridView with data from a previous demo I did along with a template column that includes a button in each row.
-->
This article has been view 11446 times.
|