开发者

Dynamically change style of panels through javascript

开发者 https://www.devze.com 2023-01-08 11:08 出处:网络
I am trying to display a new panel after the user clicks an add button, for some reason this is not working (it refreshes the page as well, even though my button has a return true)I have tried differe

I am trying to display a new panel after the user clicks an add button, for some reason this is not working (it refreshes the page as well, even though my button has a return true) I have tried different ways, but nothing seems to work that well.

<asp:Button ID="btnAdd" runat="server" Text="Add Property" CssClass="btn" OnClientClick="addProperty(); return false;"  />


 <script type="text/javascript">
    var num = 1;
    function addProperty()
    {
    num++;
    var panelName = "<%=pnlProperty"  + num.toString() + ".ClientID%>";
    alert(panelName);
    document.getElementById(panelName).style.display="inline";

   开发者_运维百科 }
        </script>

Any helps would be great!


You cannot interact javascript and ASP.NET like that. ASP.NET will always execute before the code is being sent to the client, where the javascript executes. You can use .NET to generate javascript.

In your case, this will execute before anything else:

<%=pnlProperty" + num.toString() + ".ClientID%>

It will not execute in a loop, because it is executed as ASP.NET code before the loop is generated and sent to the client. Nor will the value of the javascript variable num be used to create a panel, because javascript hasn't started executed. Everything within <%, ... %> will be interpreted as .NET code. So .NET will simply throw an error, because the above is not an accurate line of code.

You need to write your .NET code so that it generates meaningful javascript.

You could do something like this:

var panels = [
   "<%= pnlProperty0.ClientID %>",
   "<%= pnlProperty1.ClientID %>",
   "<%= pnlProperty2.ClientID %>"
];

... which might generate javascript that looks something like

var panels = [
   "ctl00_main_pnlProperty0",
   "ctl00_main_pnlProperty1",
   "ctl00_main_pnlProperty2"
];

... which is an entirely accurate way of creating an array of strings that you can then use in your javascript

document.getElementById(panels[num]).style.display="inline";

If you want a dynamic loop, you may have to do something like

var panels = "<%
    String.Join(
        ",",
        Page.Controls.OfType<Panel>()
                     .Where(panel => panel.ID.StartsWith("pnlProperty"))
                     .Select(panel => panel.ClientID).ToArray());
%>";

... which might create something like

var panels = "ctl00_main_pnlProperty0,ctl00_main_pnlProperty1,ctl00_main_pnlProperty2";

upon which you could then do:

var panelNames = panels.split(',');
document.getElementById(panelNames[num]).style.display="inline";


Based on what you're code, wouldn't a plain html button suffice?

<input type="button" value="Add Property" onclick="addProperty();" />
0

精彩评论

暂无评论...
验证码 换一张
取 消