how to do show and hide div in javascript and simillarly in c# pageload how to call div based on id value.can any one help on this ?
<ul>
<li>cat1</li>
<li>cat2</li>
<li>cat3</li>
</ul>
<div id="cat1">
<asp:UpdatePanel>
<asp:Panel>
<asp:ListView>
</asp:ListView>
</asp:Panel>
</asp:UpdatePanel>
</div>
<div id="cat2">
<asp:UpdatePanel>
<asp:Panel>
<asp:ListView>
</asp:ListView>
</asp:Panel>
</asp:UpdatePanel>
</div>
<div id="cat3">
<asp:UpdatePanel>
<asp:Panel>
<asp:ListView>
</asp:ListView>
</asp:Panel>
</asp:UpdatePanel>
</div>
To reference the div in C# codebehind, you will need to add a runat="server" attribute to the div. You can then reference it by ID in the Page_Load method. You should also set ClientIDMode="Static" for the div, to fix the ID for the div so that you can reference it in Javascript. Beware of ID collisions for static IDs.
Using strict Javascript, you can hide the div like this:
var elem = document.getElementById('cat1');
elem.style.display = 'none';
And you can show the div like this:
var elem = document.getElementById('cat1');
elem.style.display = 'block';
JQuery is probably a better way to go though than the getElementById approach:
$('#cat1').hide();
and
$('#cat1').show();
function showDiv()
{
// This is to show the div
document.getElementById('divId').style.display = 'block';
}
function hideDiv()
{
// This is to hide the div
document.getElementById('divId').style.display = 'none';
}
The code won't support, if the div has the runat property..
Hope this will help you..
Related
So here's the deal, I've got this DropDownList on my Login.aspx page, using that DropDown I'd like to set the background for the whole website. Having a MasterPage I just thought I should set the color of the body.
Here's my html for the <asp:DropDownList>:
<div class="col-sm-3 col-sm-offset-4" style="margin-bottom: 10px">
<div class="input-group input-group-sm">
<asp:Label runat="server" ID="lblColor" ClientIDMode="Static" AssociatedControlID="ddlColor" class="input-group-addon"><span class="glyphicon glyphicon-star"></span></asp:Label>
<%--Update Panel за цветовете--%>
<asp:UpdatePanel runat="server" ID="updateColor" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddlColor" style="width:100%" ClientIDMode="Static" AutoPostBack="true" OnSelectedIndexChanged="ddlColor_SelectedIndexChanged" aria-describedby="lbColor" data-taggle="dropdown" data-style="DropDownListHint-datastyle" class="btn dropdown-toggle DropDownListHint-datastyle">
<asp:ListItem Text="Бял" Value="White" Selected="True" />
<asp:ListItem Text="Зелен" Value="Green" />
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
There's 2 problem I'm experiencing.
1st one being that when I set the color of the body, after clicking on the Login button the color gets removed on the next page.
2nd one being that I can't get the page not to flash even when using an update panel.
Here's my C# code-behind.
protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
{
var body = Master.FindControl("bodyMasterPage") as HtmlGenericControl;
if (ddlColor.SelectedValue == "Green")
{
body.Style.Add("background-color", "#D2F6E2!important");
}
else if (ddlColor.SelectedValue == "White")
{
body.Style.Add("background-color", "#ccc!important");
}
updateColor.Update();
}
Any help would be greatly appreciated <3
I'll try to keep this as simple as possible. I would expect you to build off of the example below.
First, let's just build a simple <select>, like so:
<select id="ddlColor" class="form-control">
<option value="#d2f6e2">Бял</option>
<option value="#ccc">Зелен</option>
</select>
I've pulled the values from your code-behind, and we'll see why in a moment.
Second, let's build a jQuery event handler for when the select's value changes:
$('#ddlColor').on('change', function(e){
});
I'm assuming jQuery is available since I see Bootstrap CSS classes in your markup, which normally means you're also using bootstrap.js somewhere, which has jQuery as a dependency.
Third, we grab the select's selected value, and use the jQuery .css() function to apply your style to the body element:
$('#ddlColor').on('change', function(e){
var color = $(this).val();
$('body').css('background-color', color);
});
This goes anywhere in your page that you either already have scripts or you can add a script tag, as long as the script is after you've loaded jQuery.
As a note, the CSS function doesn't seem to like those !important modifiers, so I removed them. If you absolutely need them, I'd think about creating some classes for these colors instead, and use the addClass and removeClass functions instead.
Demo: https://jsfiddle.net/hfrjufto/
And a version that persists the value in localStorage: https://jsfiddle.net/hfrjufto/3/
if(!localStorage.getItem('bgcolor')) {
populateStorage();
} else {
setStyles();
}
function setStyles() {
var color = localStorage.getItem('bgcolor');
$('body').css('background-color', color);
}
function populateStorage() {
localStorage.setItem('bgcolor', $('#ddlColor').val());
setStyles();
}
$('#ddlColor').on('change', function(e) {
populateStorage();
});
In the design of web form I have four divs
divGeneralDetails
divLanguageDetails
divLinkDetails
divOperationalDetails
Divs mentioned above are displayed vertically in the form.
My question is.
Depending on value in query string, i will have to change the order in which divs are displayed.
In my Page_Load event
string FirstDiv = Request.QueryString["id"];
if value of FirstDiv is equal to "General"
then order should be
- divGeneralDetails
- divLanguageDetails
- divLinkDetails
- divOperationalDetails
if value of FirstDiv is equal to "Operational"
then order should be
- divOperationalDetails
- divGeneralDetails
- divLanguageDetails
- divLinkDetails
How do I set this in Page_Load event. Any help will be highly appreciated.
Thanks
You can use Panel.
Example:
<asp:Panel ID="panelMain" runat="server">
<asp:Panel ID="divGeneralDetails" runat="server"></asp:Panel>
<asp:Panel ID="divLanguageDetails" runat="server"></asp:Panel>
<asp:Panel ID="divLinkDetails" runat="server"></asp:Panel>
<asp:Panel ID="divOperationalDetails" runat="server"></asp:Panel>
</asp:Panel>
And then rearrange it add code behind:
panelMain.Controls.Clear();
panelMain.Controls.Add(divOperationalDetails);
panelMain.Controls.Add(divGeneralDetails);
panelMain.Controls.Add(divLanguageDetails);
panelMain.Controls.Add(divLinkDetails);
If you want to do it server-side, then for good working of ViewState (if it is being used) the Divs would have to be added in the desired order using Page.Controls.Add() in the PreInit event of the Page. Any later may throw off ViewState.
A totally different approach would be to use jQuery in the browser to manipulate the Divs, see the snippet below for one way to achieve this:
function moveOperationalToTop() {
var specialId = "divOperationalDetails";
var $main = $("#divMain");
var $divs = $main.find('div');
$main.empty();
$divs.each(function() {
if (this.id == specialId) $main.append($(this));
});
$divs.each(function() {
if (this.id != specialId) $main.append($(this));
});
}
#divOperationalDetails {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divMain">
<div id="divGeneralDetails">divGeneralDetails</div>
<div id="divLanguageDetails">divLanguageDetails</div>
<div id="divLinkDetails">divLinkDetails</div>
<div id="divOperationalDetails">divOperationalDetails</div>
</div>
<button onclick="moveOperationalToTop()">Move Operational to top</button>
well how the title says, how can I add various <li> tags to a <ul> tag from code behind. I tried this Add to List from codebehind C# Asp.net this is my example code.
ASP
<body>
<form id="form1" runat="server">
<div>
<ul id="menu" runat="server"> </ul>
</div>
</form>
And code behind.
protected void Page_Load(object sender, EventArgs e)
{
CreateMenu();
}
protected void CreateMenu()
{
HtmlGenericControl li = new HtmlGenericControl("li");
menu.Controls.Add(li);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "login.aspx");
anchor.InnerText = "login";
li.Controls.Add(anchor);
}
Well it works perfectly but maybe this gonna be a dumb question, how can I add more than one element to the <ul> tag? I need to create an new object for each item (I think this is wrong) or exist a better way to do this?
I searched but any example satisfies my doubt, sorry if you think is a repeated question.
If your datas(menu items) are not coming from a source(something like database), you need to repeat the same process over and over again unfortunately. Or you can create a function which is taking 2 parameters, text and link. This way you can do this job with 1 line.
private void AddMenuItem(string text, string link)
{
HtmlGenericControl li = new HtmlGenericControl("li");
menu.Controls.Add(li);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", link);
anchor.InnerText = text;
li.Controls.Add(anchor);
}
AddMenuItem("text","link");
AddMenuItem("text2","link2");
AddMenuItem("text3","link3");
You can improve this for your specific needs.
You can use ListView. It's easier format. I also found a good tutorial about it (http://weblogs.asp.net/scottgu/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui)
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div>
<p class="name"><%# Eval("author") %></p>
<p class="date"><%# Eval("insertDate") %></p>
</div>
<p class="comment"><span class="<%# Eval("icon") %>"></span><%# HttpUtility.HtmlEncode(Eval("comment")) %></p>
</li>
</ItemTemplate>
</asp:ListView>
I hope someone can give me a hint about what should I do in this case. I want to show a notification email. I have a timer that fires passing a time. If someone mouseover the linkbutton then will show all the emails and if out then dissapears. The fact is when I am trying to select one of the emails the content (which has the emails) dessapears because of the mouseout. What should I do to avoid this? Thanks in advance!!! by the way I get my emails at onmouseover and close on out.
<asp:Timer ID="TimerNew" runat="server" Interval="10000" OnTick="TimerNew_Tick" Enabled="false"></asp:Timer>
<asp:Panel ID="PanelTools" runat="server" >
<div runat="server" id="DropDownMenu">
<asp:LinkButton ID="LinkButton" runat="server" onmouseover="OnClientMouseOver()" onmouseout="OnClientMouseOut()">
</asp:LinkButton>
<div id="divEmails" runat="server">
<div class="dropdown-content">
<ul id="emailList" runat="server">
</ul>
</div>
</div>
</div>
</asp:Panel>
Here is my javascript function.
function OnClientMouseOver(obj, event)
{
var isOpen = '<%= this.Open %>';
if (isOpen == false)
{
__doPostBack('OpenEmails');
}
}
function OnClientMouseOut(obj, event)
{
var isOpen = '<%= this.Open %>';
var e = event.toElement || event.relatedTarget;
if (e.parentNode == this || e == this)
{
return;
}
__doPostBack('CloseEmails');
}
this.Open is a variable (viewstate to dont lose it). I use telerik RadAjaxProxyManager, I do an ajax postback and execute my server methods.
I have a div with style="display:none". The div should become visible on pressing an html button:
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
<div style="float:left">
<div id="ctl00_MainContent_upnlLbRD">
<select size="4" name="ctl00$MainContent$lbRD" id="ctl00_MainContent_lbRD" style="width:188px;">
<option value="5">one</option>
<option value="1">two</option>
</select>
<input id="btnAdd" type="button" value="Добавить" onclick="JSAdd();" />
<input id="btnEdit" type="button" value="Редактировать" onclick="JSEdit();" />
</div>
<div id="ctl00_MainContent_divDetail" style="display:none" clientidmode="static">
<div id="ctl00_MainContent_upnlDescription">
<div>
<span id="ctl00_MainContent_lblDescription">Описание:</span>
<input name="ctl00$MainContent$txtDescription" type="text" id="ctl00_MainContent_txtDescription" />
<span id="ctl00_MainContent_txtDescriptionRequiredFieldValidator" style="color:Red;visibility:hidden;">Описание является обязательным для заполнения</span>
</div>
<input type="submit" name="ctl00$MainContent$btnSave" value="Сохранить" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$btnSave", "", true, "", "", false, false))" id="ctl00_MainContent_btnSave" />
I need to be able to make the div invisible again from code-behind. I cannot access the div unless it is runat="server". But when I add runat="server", the div doesn't become visible on pressing the button from the javascript function above. Could you please help me with this?
Thanks,
David
You can access a div in code-behind by adding the runat="server" attribute. Adding this attribute does change the way you access the element in JavaScript though:
var el = document.getElementById("<%=div1.ClientID%>");
if (el){
el.style.display = "none"; //hidden
}
There are two ways to adjust the visibility from code-behind, but since you're setting display:none in JavaScript, you'd probably want to use the same approach in code-behind:
div1.Style["display"] = "block"; //visible
In code-behind, you can also set the Visible property to false, but this is different because it will prevent the element from being rendered at all.
EDIT
If the div is still showing with display:none present, you probably have an unclosed tag or quote somewhere affecting the markup. Double check and make sure that the markup is valid.
Use a Panel, it renders as a classic div
<asp:Panel runat="server" ID="divDetail" ClientIDMode="Static" />
You have a few options, use ClientIDMode="Static" or use the dynamic ClientID at run-time. Both of these options give you server-side access to the object.
Dynamic:
<div id="divDetail" runat="server" />
//or
<asp:panel id="divDetail" runat="server" />
function JSAdd() {
document.getElementById('<%= divDetail.ClientID %>').style.display = "block";
}
//to hide from code-beind
divDetail.Attributes.Add("style","display:none;");
Static(.NET 4.0 +):
<div id="divDetail" runat="server" ClientIdMode="Static">
//or
<asp:panel id="divDetail" runat="server" ClientIdMode="Static" />
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
When runat="server" is applied to an element, asp.net ensures that it has a unique ID by mangling it. Simply ask asp.net for the real client id:
function JSAdd() {
document.getElementById("<%=div1.ClientID%>").style.display = "block";
}
Alternatively, you could tell asp.net to leave your ID alone by adding this to your div:
<div id="div1" runat="server" clientidmode="Static">
Resources:
ClientIdMode="Static" docs
In ASP.NET, to make IDs unique (if multiple control loaded where same ID are specified), ID on elements are often follow a convention like ctl00_container1_container2_controlID and this is what returned when you call control.ClientID.
If you consider such a case where there's same ID on the serverside and you loaded those two controls in your page, you may consider using jQuery and life would be easier with runat="server" with just matching the ID with the end part:
function JSAdd() {
$("div[id$=divDetails]").show();
}
Simplest technique will be to use Javascript/Jquery to Changes Display property of the Div. if not that you can use following code
<form method="post" runat="server">
<div style = "display:none" id= "div1" runat ="server" >Hello I am visible</div>
<asp:Button Text="display Div" runat ="server" ID ="btnDisplay" OnClick = "displayDiv" />
<asp:Button Text="display Div" runat ="server" ID ="btnHideDiv" OnClick = "hideDiv" />
</form>
code behind code is as follows
protected void displayDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "block");
}
protected void hideDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "none");
}
guess you Got your solution