Accessing <div> from both javascript and code-behind - c#

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

Related

Problems with setting the background of the whole website with a DropDownList

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();
});

Cant get values of inputs asp.net

My problem i always get null from my inputs or default value. Some how if i set value at page_load like Form_txt_Ad.Value="ExampleValue"; i can get it. But i cant get any value from inputs.
protected void Save_Button_Click(object sender, EventArgs e)
{
string exapmle = Form_txt_Ad.Value;
string example = Form_txt_Soyad.Value;4
}
<div class="input">
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" runat="server" />
<span><i class="glyphicon glyphicon-user"></i></span>
</div>
<div class="col-md-12" style="text-align: center;">
<button type="button" runat="server" onserverclick="Save_Button_Click" class="btn btn-success btn-raised btn-lg" title="Kaydet"><i class="glyphicon glyphicon-floppy-saved icon-marginRight"></i>Kaydet</button>
</div>
Thx for help.
Make sure all your control elements are placed inside <form> ... </form> tag.
Since you have placed runat="server" you should be able to get the value by either using any of them
Form_txt_Ad.Value
(OR)
Form_txt_Ad.Text
Else use Request.Form["Form_txt_Ad"]
Not sure though why not use a server side control using <asp:TextBox ... which will allow you to get the textbox value directly using the Text property
Add the name attribute to your input and make sure it's inside a form element.
<form>
...
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" name="Form_txt_Ad" runat="server" />
...
</form>

Textchange event not working

I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>

javascript show hide div

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..

How to show pop up div from server side on button click

I am working on Payment page and i want to show a popup for showing message your payment is processing. so for now i am using CustomValidator and Submit Button. and i want to show this popup when Args is valid. my code is.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" OnServerValidate="CustomValidator1_ServerValidate"
EnableClientScript="true" ValidationGroup="Authorize"></asp:CustomValidator>
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true" CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click" OnClientClick="validate(ContentPlaceHolder1_chk_agree);" />
One better approach is to go with "updateProgress".
Place your submit button inside a updatePanel and place a loading gif image inside updateProgress which will show below loading image when payment progress is going on and will close automatically when payment is complete.
Loading ....
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/loadingNew.gif" AlternateText="Loading ..." ToolTip="Loading ..."/>
</ProgressTemplate>
</asp:UpdateProgress>
To show a message box after validation, you can do the following:
Add the following javascript to your <head>
<script language="javascript">
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
alert('Your payment is processing');
}
return isValid;
}
</script>
Then, change your button like this:
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true"
CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click"
OnClientClick="return SubmitButton_ClientClick();" />
An even better approach is to use a popup div - here is a very basic example:
Add this somewhere in your <body>
<div id="popup_box" style="height:300;width:300;position:absolute;top:150;left:350;border:3px solid red;background:#d8d8d8;display:none;">
<h1>Payment is processing</h1>
<button id="popupBoxClose" onclick="document.getElementById("popup_box").style.display = 'none';">Close</button>
</div>
And modify the SubmitButton_ClientClick like this:
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
document.getElementById("popup_box").style.display = '';
}
return isValid;
}

Categories

Resources