locked
Hiding control from code behind or javascript RRS feed

  • Question

  • User-1865833014 posted

    Hi

    I'm having an issue here, where I'm trying to hide something based on SelectedValue in a DropDownList. My knowledge on JavaScript is extremely limited, so I have tried using code behind, which I managed to get working on other pages

    The actual page is large, but I have tried to remove all unneeded parts of the aspx page

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="sup_room_heat.aspx.vb" Inherits="client_sup_room_heat"
    	EnableViewState="true" MaintainScrollPositionOnPostback="true" %>
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
    	<title>Untitled Page</title>
    
    	<script type="text/javascript">
            function SetVisibilityEstimatedAge(ddl, tr)
            {
                alert("Start");
                //var elem = document.getElementById("security_question_1");
                ddl.onchange = function (){
                    alert("Change");
                    //var hiddenDiv = document.getElementById("tr_estimatedAge");
                    tr.style.display = (this.value == "") ? "none":"block";
                };
            }
    	</script>
    </head>
    <body style="padding-top: 0px; margin-top: 0px;">
    	<form id="form1" runat="server">
    
    	<asp:ScriptManager ID="ScriptManager1" runat="server">
    		<Scripts>
    			<asp:ScriptReference Path="../js/AsyncPostbackUtility.js" />
    		</Scripts>
    	</asp:ScriptManager>
    	
    	<asp:Panel ID="pnlSupRoomHeat" runat="server" Visible="true" Style="width: 98%; padding: 5px">
    		<asp:UpdatePanel ID="upSupRoomHeatForm" UpdateMode="Conditional" runat="server" RenderMode="Inline">
    			<ContentTemplate>
    				<asp:FormView ID="fvSupRoomHeat" runat="server" DefaultMode="Edit" CssClass="FormView_Css"
    					DataSourceID="sqlSupRoomHeat" Width="98%" OnDataBound="fvSupRoomHeat_DataBound"
    					OnItemCommand="fvSupRoomHeat_ItemCommand" DataKeyNames="LabelID,BuildID,IdentID">
    
    					<EditItemTemplate>					
    						<asp:Panel runat="server" ID="pnlSupRoomHeatDetail">
    							<table cellspacing="0" border="0" style="width: 100%; border-collapse: collapse;">
    								<tr style="vertical-align: top;">
    									<td style="width: 49%; padding: 0px">
    										<asp:Panel runat="server" ID="pnlSupRoomHeatStatus">
    											<table cellpadding="2" cellspacing="0" border="0" style="width: 100%" class="ekpro_panel_box">
    												<tr class="ekpro_std tblrowalt">
    													<td width="100px">
    														<asp:Label ID="lblstatus" runat="server" Text="Type" AssociatedControlID="ddlstatus" />:
    													</td>
    													<td>
    														<asp:DropDownList ID="ddlstatus" runat="server" CssClass="ekpro_txt ekpro_field_Large DoNotMark"
    															AutoPostBack="True" OnDataBound="ddlStatus_DataBound" DataSourceID="sql_Oventypes"
    															DataValueField="stove_id" DataTextField="text" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged"
    															onchange="if(!isValid()) return false; inputGray(this);" />
    														<ekpro:HelpTip ID="HelpTip5" runat="server" typeId="10" fieldName="type" />
    													</td>
    												</tr>
                                                    <tr id="tr_estimatedAge2" class="ekpro_std tblrowalt" runat="server" >
                                                        <td class="ekpro_std">Estimeret alder 2:
                                                        </td>
                                                        <td colspan="2">
                                                            <asp:DropDownList ID="ddlEstimatedAge2" runat="server" CssClass="ekpro_txt ekpro_field_Large DoNotMark"
                                                                DataSourceID="sql_WoodStove_EstimatedAges" DataValueField="Id" DataTextField="Text" Text='<%# Bind("EstimatedAge") %>' 
                                                                OnSelectedIndexChanged="AutoSave" AutoPostBack="true" onchange="if(!isValid()) return false; inputGray(this);" />
                                                            <ekpro:HelpTip ID="HelpTip24" runat="server" typeId="10" fieldName="WoodStoveEstimatedAge" />
                                                        </td>
                                                    </tr>
    											</table>
    										</asp:Panel>
    									</td>
    								</tr>
    							</table>
    						</asp:Panel>
    					</EditItemTemplate>
    				</asp:FormView>
    			</ContentTemplate>
    		</asp:UpdatePanel>
    	</asp:Panel>
    	</form>
    </body>
    </html>
    

    And the code behind

       Protected Sub ddlStatus_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim statusddl As DropDownList = sender
    
    
            Dim tr_estimatedAge As HtmlTableRow = fvSupRoomHeat.FindControl("tr_estimatedAge2")
            Dim ddlEstimatedAge2 As DropDownList = fvSupRoomHeat.FindControl("ddlEstimatedAge2")
            Dim pnlSupRoomHeatStatus As Panel = fvSupRoomHeat.FindControl("pnlSupRoomHeatStatus")
    
    
            If (statusddl.SelectedValue = 4 OrElse statusddl.SelectedValue = 5) Then
                '' tr_estimatedAge.Attributes("class") = "ekpro_std tblrowalt"
                'tr_estimatedAge.Visible = True
                ddlEstimatedAge2.Enabled = True
            Else
                ' tr_estimatedAge.Attributes("class") = "remove"
                ' tr_estimatedAge.Visible = False
                ddlEstimatedAge2.Enabled = False
            End If
        End Sub

    First I tried to just change the class of the table row. Setting class to 'remove' hides the tablerow if I set it in the aspx file (and it works in other aspx files)

    I also tried just set it Visible to false, but it doesn't do anything

    As a last resort I tried to just set the DropDownList to disabled, but this one also doesn't work

    I also started a bit on some javascript, but I had no idea on how to continue, so I also got a bit lost there

    What I'm trying to accomplish is to hide the <tr> completely, if the selected value of ddlstatus is different than 4 or 5

    The interesting thing here is that I can clearly see that the controls I find in the code behind, is the same ones as in the aspx file. When I'm looking at the class attribute, it's set to what I wrote on the aspx page. When I'm changing the class I can also see the change happening in the "Watch" window, but when I'm hitting F12 in the browser and looks at the <tr> segment, the class did not change at all. Seems like the change happening in the code behind is not sent back to the client

    Saturday, August 31, 2019 10:54 AM

Answers

  • User-1865833014 posted

    I wasn't able to get any further by using code behind, so I tried with javascript and have something that almost works

    In the bottom of my aspx page (just before </body> I added the following code

    <script>
            function SetVisibilityProductionYear(test)
            {
             
                var d = document.getElementById("fvSupRoomHeat_ddlstatus").value;
                var tr = document.getElementById("fvSupRoomHeat_tr_productionYear2");
                alert(d);
                if (d == 4 || d == 5 || d == 10)
                {
                    alert("Show me");
                    tr.style.display = 'inline';
                }
                else
                {
                    alert("Hide me");
                    
                    tr.style.display = 'none';
                } 
                  alert(test);
            }
    
            SetVisibilityProductionYear('load');
    
        </script>

    And I set onchange on the dropdownlist I'm calling SetVisibilityProductionYear('dropdown')

    During load of the page, it all works correctly. It will correctly hide the tablerow and display all the alert including an alert saying 'load'.

    When calling onchange it will also correctly show the alerts with 'dropdown' and 'hide me', but after this I'm noticing the page loads again (SelectedIndexChanged calls a method in code behind, which is probably causing this), but during this reload of the page it does not call SetVisibilityProductionYear('load'); as I would expect

    EDIT:

    A quick google search gave me the last information I needed. All I needed to do was to add the following to make it call the method after postback:

       function pageLoad(sender, args)
        {
            SetVisibilityProductionYear('Load');
        }

    Thanks for the help, even though I ended up in the other direction

    smile

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 4, 2019 9:49 AM

All replies

  • User288213138 posted

    Hi Adagio_Botjek,

    I modified your code according to your description.

    I used Attributes.Add("style", "display:none"); to hide the tr.

    The code:

    Protected Sub ddlstatus_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim dr1 As DropDownList = CType(fvSupRoomHeat.FindControl("ddlstatus"), DropDownList)
        Dim tr_estimatedAge As HtmlTableRow = CType(fvSupRoomHeat.FindControl("tr_estimatedAge2"), HtmlTableRow)
    
        If dr1.SelectedValue = "4" OrElse dr1.SelectedValue = "5" Then
            tr_estimatedAge.Attributes.Add("style", "display:none")
        End If
    End Sub
    

    The result:

    Best regards,

    Sam

    Monday, September 2, 2019 7:35 AM
  • User-1865833014 posted

    Hi samwu

    Thanks, but unfortunately this doesn't do it either. I believe my problem is that ANY changes to the control in code behind, does not reflect into the actual aspx page

    This is what is happening. First when I open the page, press F12 to see the source code, I see this class where I just added some text, that should go away after executing my code

    When debugging in my code, I can clearly see that I have found the correct control, as the class information here is the same as on the actual page.

    After stepping through the code, I can see the class attribute has now changed. My crazy string from before is now gone.

    Unfortunately when the code behind is finished and I go back to my code, the class has not changed at all. This was exactly the same as when I tried to use the code you posted

    I forgot to post it in my first post, but my css file has the following:

    .remove
    {
        display: none;
    }

    Monday, September 2, 2019 9:41 AM
  • User288213138 posted

    Hi Adagio_Botjek,

    According to your description, I tested your code, but it work fine in my side.

    The code:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm55.aspx.cs" Inherits="case_solution.Test_Code3.WebForm55" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style>
            .remove {
                display: none;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server">
    		<Scripts>
    			<asp:ScriptReference Path="../js/AsyncPostbackUtility.js" />
    		</Scripts>
    	</asp:ScriptManager>
    	
    	<asp:Panel ID="pnlSupRoomHeat" runat="server" Visible="true" Style="width: 98%; padding: 5px">
    		<asp:UpdatePanel ID="upSupRoomHeatForm" UpdateMode="Conditional" runat="server" RenderMode="Inline">
    			<ContentTemplate>
    				<asp:FormView ID="fvSupRoomHeat" runat="server" DefaultMode="Edit" CssClass="FormView_Css" Width="98%">
    
    					<EditItemTemplate>					
    						<asp:Panel runat="server" ID="pnlSupRoomHeatDetail">
    							<table cellspacing="0" border="0" style="width: 100%; border-collapse: collapse;">
    								<tr style="vertical-align: top;">
    									<td style="width: 49%; padding: 0px">
    										<asp:Panel runat="server" ID="pnlSupRoomHeatStatus">
    											<table cellpadding="2" cellspacing="0" border="0" style="width: 100%" class="ekpro_panel_box">
    												<tr class="ekpro_std tblrowalt">
    													<td width="100px">
    														<asp:Label ID="lblstatus" runat="server" Text="Type" AssociatedControlID="ddlstatus" />:
    													</td>
    													<td>
    														<asp:DropDownList ID="ddlstatus" runat="server" CssClass="ekpro_txt ekpro_field_Large DoNotMark"
    															AutoPostBack="True" OnSelectedIndexChanged="ddlstatus_SelectedIndexChanged">
                                                                <asp:ListItem>1</asp:ListItem>
                                                                        <asp:ListItem>2</asp:ListItem>
                                                                        <asp:ListItem>3</asp:ListItem>
                                                                        <asp:ListItem>4</asp:ListItem>
                                                                        <asp:ListItem>5</asp:ListItem>
    														</asp:DropDownList>
    														<%--<ekpro:HelpTip ID="HelpTip5" runat="server" typeId="10" fieldName="type" />--%>
    													</td>
    												</tr>
                                                    <tr id="tr_estimatedAge2" class="ekpro_std tblrowalt" runat="server" >
                                                        <td class="ekpro_std">Estimeret alder 2:
                                                        </td>
                                                        <td colspan="2">
                                                            <asp:DropDownList ID="ddlEstimatedAge2" runat="server" CssClass="ekpro_txt ekpro_field_Large DoNotMark" AutoPostBack="true" />
                                                            <%--<ekpro:HelpTip ID="HelpTip24" runat="server" typeId="10" fieldName="WoodStoveEstimatedAge" />--%>
                                                        </td>
                                                    </tr>
    											</table>
    										</asp:Panel>
    									</td>
    								</tr>
    							</table>
    						</asp:Panel>
    					</EditItemTemplate>
    				</asp:FormView>
    			</ContentTemplate>
    		</asp:UpdatePanel>
    	</asp:Panel>
        </form>
    </body>
    </html>
    
    
    aspx.cs:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If Not IsPostBack Then
                Dim dt As DataTable = New DataTable()
                dt.Columns.AddRange(New DataColumn(2) {New DataColumn("CustomerId"), New DataColumn("Name"), New DataColumn("Country")})
                dt.Rows.Add(1, "name1", "country1")
                dt.Rows.Add(2, "name2", "country2")
                dt.Rows.Add(3, "name3", "country3")
                fvSupRoomHeat.DataSource = dt
                fvSupRoomHeat.DataBind()
            End If
        End Sub
    
        Protected Sub ddlstatus_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim dr1 As DropDownList = CType(fvSupRoomHeat.FindControl("ddlstatus"), DropDownList)
            Dim tr_estimatedAge As HtmlTableRow = CType(fvSupRoomHeat.FindControl("tr_estimatedAge2"), HtmlTableRow)
    
            If dr1.SelectedValue = "4" OrElse dr1.SelectedValue = "5" Then
                tr_estimatedAge.Attributes("class") = "ekpro_std tblrowalt"
            Else
                tr_estimatedAge.Attributes("class") = "remove"
            End If
        End Sub

    Best regards,

    Sam

    Tuesday, September 3, 2019 9:50 AM
  • User-1865833014 posted

    Hi Sam

    That's weird. Seems like it is some of the parts that I cut away that causes it, which are mostly just other fields, some sql datasources and then some javascript files. Sounds like the problem might lie in javascript, where most of them are jquery files. I guess I need to dive into those to find what is causing it

    Thanks for the help

    smile

    Tuesday, September 3, 2019 1:40 PM
  • User288213138 posted

    Hi Adagio_Botjek,

    <Scripts>
    			<asp:ScriptReference Path="../js/AsyncPostbackUtility.js" />
    		</Scripts>

    What is this code for?

    and in your post code, I found that there was no call function SetVisibilityEstimatedAge(ddl, tr).

    You can use F12 to check the Response in the NetWork to find out what has been updated.

    Best regards,

    Sam

    Wednesday, September 4, 2019 2:13 AM
  • User-1865833014 posted

    Hi Sam

    I'm not quite sure what AsyncPostbackUtility.js is used for yet, but removing it doesn't make any difference. I don't have any call for SetVisibilityEstimatedAge, as I have no idea how to get started here

    There is some other code that I excluded, that I thought didn't have anything to do with this (this is some code that is on all pages in my project, but this hiding/showing stuff from codebehind works just fine on other pages). In the header of the page I have these two lines:

    <ekpro:IncludeCss runat="server" ID="IncludeCss" />
    <ekpro:IncludeJs runat="server" ID="IncludeJs" />

    And then I have this:

    <%@ Control Language="VB" AutoEventWireup="false" CodeFile="IncludeJsControl.ascx.vb" Inherits="client_v5_usercontrols_IncludeJsControl" %>
    <script src="/js/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="/js/jquery.validate.js?20160701" type="text/javascript"></script>
    <script src="/js/Scripts.js?20150204bad9" type="text/javascript"></script>

    The scripts.js file includes the following code (there were a lot more lines, but I have removed them from my code to try to pinpoint the problem)

    var helpTipHandler = {
    
        hasTip: function (typeId, fieldName) {
            if (typeof helpTips === 'object') {
                tips = helpTips;
                for (var i = 0; i < tips.length; i++) {
                    if (tips[i].typeId == typeId && tips[i].fieldName == fieldName) return true;
                }
            }
            return false;
        },
    
        getTip: function (typeId, fieldName) {
            if (typeof helpTips === 'object') {
                tips = helpTips;
                for (var i = 0; i < tips.length; i++) {
                    if (tips[i].typeId == typeId && tips[i].fieldName == fieldName) return tips[i].html;
                }
            }
            return '';
        }
    };
    
    /* gray out inputfield */
    function inputGray(i) {
    	$(i).css("background-color", "gray");
    }

    If I remove any of the lines from IncludeJsControl, then for some reason it will not call the method in the codebehind file where I'm setting visibility

    Looking at the network activity didn't help me much. I could just see the aspx page that was returned didn't include the changed class

    Wednesday, September 4, 2019 6:37 AM
  • User-1865833014 posted

    I wasn't able to get any further by using code behind, so I tried with javascript and have something that almost works

    In the bottom of my aspx page (just before </body> I added the following code

    <script>
            function SetVisibilityProductionYear(test)
            {
             
                var d = document.getElementById("fvSupRoomHeat_ddlstatus").value;
                var tr = document.getElementById("fvSupRoomHeat_tr_productionYear2");
                alert(d);
                if (d == 4 || d == 5 || d == 10)
                {
                    alert("Show me");
                    tr.style.display = 'inline';
                }
                else
                {
                    alert("Hide me");
                    
                    tr.style.display = 'none';
                } 
                  alert(test);
            }
    
            SetVisibilityProductionYear('load');
    
        </script>

    And I set onchange on the dropdownlist I'm calling SetVisibilityProductionYear('dropdown')

    During load of the page, it all works correctly. It will correctly hide the tablerow and display all the alert including an alert saying 'load'.

    When calling onchange it will also correctly show the alerts with 'dropdown' and 'hide me', but after this I'm noticing the page loads again (SelectedIndexChanged calls a method in code behind, which is probably causing this), but during this reload of the page it does not call SetVisibilityProductionYear('load'); as I would expect

    EDIT:

    A quick google search gave me the last information I needed. All I needed to do was to add the following to make it call the method after postback:

       function pageLoad(sender, args)
        {
            SetVisibilityProductionYear('Load');
        }

    Thanks for the help, even though I ended up in the other direction

    smile

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 4, 2019 9:49 AM
  • User944797201 posted

    Well done! And actually I like your way of thinking :)

    Thursday, December 19, 2019 9:01 AM