Am using the below code to assign the label text using javascript. It's working well. But i can't able to read the label text in code behind. Please help me to fix this issue.
Javascript:
==========
var lbl_total = document.getElementById('<%= lbl_total.ClientID %>');
lbl_total.innerHTML = '500';
c# code behid :
===============
string total = lbl_total.Text; //It always return "";
client side changes for label will not get reflected in server side as its data is not posted to server. So the solution is to take an input hidden control and set its value with label's updated value. Below is the sample code:
<script type="text/javascript">
$(document).ready(function() {
var total = 0;
$('#Button1').click(function() {
total += 150;
$("span[id$=lbl_TotalCount]").html(total);
$("input:hidden[id$=MyHidden]").val(total);
});
});
</script>
html
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
<asp:Button ID="btn_saveForm" runat="server" Text="save" CssClass="btnForm" OnClick="btn_saveForm_Click" />
<asp:Label ID="lbl_TotalCount" Style="color: #00e4ff; font-family: Arial; font-weight: bold;
text-decoration: underline" runat="server" Text="0">
</asp:Label>
<asp:HiddenField ID="MyHidden" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
full Article : Get label value in code behind whose text is changed via JavaScript/jQuery
Related
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>
I am using AjaxFileUpload control on an ASP.net web form. On the OnClientUploadComplete event, I am updating a label using
document.getEleemntById("<%=TestLabel.ClientId%>").innerText="someText"
This works fine in Google Chrome and Internet Explorer (lable updates fine after upload is complete). However, in Firefox , the debugger shows element not found error right at the document.getElementID.
<script type="text/javascript">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload"
OnUploadComplete="UploadComplete"
runat="server" OnClientUploadComplete="UploadCompleteClient" OnClientUploadStart="UploadStartClient" MaximumNumberOfFiles="1" />
<script type="text/javascript">
function UploadStartClient() {
}
function UploadCompleteClient(sender, args) {
//alert("upload complete");
document.getElementById("TestLabel").innerText = "test text";
}
</script>
The above is a snippet of my code. Based on some of the answers on stack overflow,
I tried placing the java script at the end of the page
and surrounding the script by $(document).ready(function(){}.
But these approaches did not work as the label is not updated after the upload completes. I vaguely understand that this is because of how page elements are handled differently in Firefox as compared to that in Chrome or IE. Please suggest where I am going wrong with this and how I can get the label to update
edit
This is my aspx page
<asp:Content runat="server" ContentPlaceHolderID = "Mainform">
<form id="Form1" runat="server" style="border-style: hidden; border-color: inherit; border-width: medium; width: 717px; height: 606px; ">
<ajaxToolkit:ToolkitScriptManager ID="ScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>
<p>
Upload:
</p>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload" OnUploadComplete="ProcessUpload" runat="server" OnClientUploadComplete="UploadCompleteClient" OnClientUploadStart="UploadStartClient" MaximumNumberOfFiles="1" />
<p>
</p>
<p>
<label id="TestLabel"></label> 
</form>
<script type="text/javascript">
function UploadStartClient() {
}
function UploadCompleteClient(sender, args) {
//alert("upload complete");
document.getElementById("<%=TestLabel.ClientID%>").text = "test Message";
}
</script>
</asp:Content>
ASPX:
<asp:Label ID="TestLabel" runat="server"></asp:Label>
JavaScript:
function UploadCompleteClient(sender, args)
{
$('#<%= TestLabel.ClientID %>').html('someText');
}
function UploadCompleteClient(sender, args) {
//alert("upload complete");
document.getElementById("TestLabel").innerText = "test text";
}
change to
function UploadCompleteClient(sender, args) {
//alert("upload complete");
document.getElementById("TestLabel").innerHTML = "test text";
}
I have an asp.net repeater that displays a title and and image.
The title is very long , so I want to display the title again on mouse over.
I tried to implement a mouse over but I have the following problem.
My display looks like this :
Repeater Element 1 Repeater Element 2
Title 1 Title 2
Image 1 Image 2
Now on doing a mouse over on Element1 , my mouse over displays Title1.
On doing a mouseover on Element2 , my mouse over displays Title1 again ,and I would like it to
display Title2 ? Can anyone point me on how i can achieve this.
My code is below :
<asp:Repeater ID="rptMonitorSummary" runat="server" OnItemDataBound="rptMonitorSummary_OnItemDataBound">
<ItemTemplate>
<asp:Panel ID="Pnl" runat="server" onmouseover="return showsamplepopup();" onmouseout="return hidesamplepopup();">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">
<%# Eval("Name").ToString().Length > 9 ? (Eval("Name") as string).Substring(0, 9) : Eval("Name")%>
</h5>
<div id="popup" style="position: absolute; width: 80px; height: auto; background-color: Lime;
border-bottom: solid 3px gray; display: none; border-right: solid 3px gray; display: none;">
<%#Eval("Name")%>
</div>
<div class="center">
<asp:Image Width="50px" ID="btnPerformanceImage" runat="server" Height="28px"></asp:Image>
</div>
</li>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
The javascript functions are as follows :
function hidesamplepopup() {
document.getElementById('popup').style.display = 'none';
return false;
}
function showsamplepopup(e) {
e = (e) ? e : window.event;
var element = (e.target) ? e.target : e.srcElement;
var left = element.offsetLeft;
var top = element.offsetTop;
while (element = element.offsetParent) {
left += element.offsetLeft;
top += element.offsetTop;
}
document.getElementById('popup').style.display = 'block';
document.getElementById('popup').style.left = left;
document.getElementById('popup').style.top = top;
return false;
}
I do not know what is your requirement. It could have been a lot easier if you use jQuery tooltip.
This is just an alternative approach.
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$(document).tooltip();
});
</script>
<asp:Repeater ID="rptMonitorSummary" runat="server"
OnItemDataBound="rptMonitorSummary_OnItemDataBound">
<ItemTemplate>
<asp:Panel ID="Pnl" runat="server">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header" title="<%# Eval("Name").ToString() %>">
<%# Eval("Name").ToString().Length > 9 ?
(Eval("Name").ToString()).Substring(0, 9) : Eval("Name")%>
</h5>
<div class="center">
<asp:Image Width="50px" ID="btnPerformanceImage"
runat="server" Height="28px"></asp:Image>
</div>
</li>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
Notice that getElementById will return the first element with that ID. And you're using the same ID for your Div's.
You should either use a different ID for each item of the repeater (generating different ID's for each of them), or change your logic to fetch them by some other property. I highly recommend using jQuery as well.
I would change the way which you are binding the events to elements, as your sample code doesn't use jQuery I'll assume you don't want it :)
First things first, you'll want to add a class to the asp:panel so that there will be some way of identifying and selecting all the instances. Also you'll want to use classes for your popups not IDs as IDs should be unique on a page.
then you can do something like:
var elements = document.querySelectorAll('.thatClassYouAdded'),
i = 0, l = elements.length;
for(;i<l;i++)
{
elements[i].addEventListener('mouseover', function(e) {
var popup = this.querySelector('.popup');
//do some stuff to popup
});
}
It's also important to note that querySelector is not supported in legacy browsers (see https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector for more info and support table) and older IEs (pre 9) use attachEvent instead of addEventListener which you may need to write additional code to support
I have a form that calls some javascript and some code behind (C# for me) when a link button is pressed. Normal operation should act as such: Click on link button which gets text from a label on the form, opens an HTML editor, save the text by clicking 'Done' on the text editor and then displaying the text on the form again. It will do all of that, but I get an error (control is undefined) and then that prevents me from doing any other work on the form.
First, here is my aspx code, which is a window that hold the HTML editor, and the HTML editor.
<asp:Panel ID="EditCommentPopup" runat="server" SkinID="PopupPanel" HorizontalAlign="Center" Width="500px" Style="display:none;">
<div id="SendCommentHeader" class="modalPopupHeader">
<table width="100%" style="vertical-align: middle">
<tr>
<td style="width: 50%; text-align: left; padding-left: 5px;">
<asp:Label ID="EditCommentHeaderLBL" runat="server" Font-Bold="true" Text="Change Comment" ></asp:Label>
</td>
<td style="width: 50%; text-align: right; padding-right: 3px;">
<asp:Button SkinID="SubmitButton" ID="SaveComment" runat="server" Text="Done" OnClientClick="submitEditorPopup(); return true;" OnClick="SubmitCommentButton_Click"/>
<asp:Button SkinID="CancelButton" ID="cancelCommentButton" runat="server" Text="Cancel"/>
</td>
</tr>
</table>
</div>
<ajaxToolkit:ModalPopupExtender ID="EditCommentPopupExtender" runat="server" TargetControlID="EditCommentHeaderLBL"
PopupControlID="EditCommentPopup" BackgroundCssClass="modalBackground" PopupDragHandleControlID="EditCommentPopup"
DropShadow="False" CancelControlID="cancelCommentButton" BehaviorID="ChangeCommentsPopup" >
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="EditCommentInnerPanel" SkinID="PopupInnerPanel" HorizontalAlign="Center" runat="server" >
<asp:Label ID="CommandArgLBL" runat="server" Visible="false"></asp:Label>
<custom:CustomTextEditor ID="EditCommentsTextBox" runat="server" Width="100%" Height="300px" NoScript="true" />
</asp:Panel>
</asp:Panel>
Here are my javascript functions
var contentLBL;
var editorControl;
var hiddenField;
function LoadEditorPopup(labelID, editorID, hiddenID, linkID) {
editorControl = document.getElementById(editorID);
contentLBL = document.getElementById(labelID);
hiddenField = document.getElementById(hiddenID);
editorControl.control.set_content(contentLBL.innerHTML);
var popup = $find("ChangeCommentsPopup");
popup.show();
}
function submitEditorPopup() {
var tmp = editorControl.control.get_content(); //error flags here
contentLBL.innerHTML = tmp;
var str= new String();
str = tmp;
str = str.replace(/</g, "{%");
str = str.replace(/>/g, "%}"); //stripping out html tags to prevent sql insertion
hiddenField.value = str;
var popup = $find("ChangeCommentsPopup");
popup.hide();
}
And here are my C# functions
protected void ShowEditCommentPopup(object sender, EventArgs e)
{
string arg = ((LinkButton)sender).CommandArgument;
string content = "";
string title = "";
switch (arg)
{
//doing stuff, setting content and title
}
EditCommentHeaderLBL.Text = title;
CommandArgLBL.Text = arg;
EditCommentsTextBox.Content = content;
EditCommentPopupExtender.Show();
EditModalPopupExtender.Show(); //this is the form
}
So, what's happening here, I click on a linkbutton (not shown in aspx code) and it fires the LoadEditorPopup function in the javascript. It does its stuff and I have a 'return true' in the onclientclick call so that the next function, ShowEditCommentPopup, in the code behind, will be called. The editor pops up and I can use it just fine. When I click 'Done' the SubmitEditorPopup event is fired in the javascript and I get an error saying that the variable EditorControl is undefined. I have found that if I do not call the ShowEditCommentPopup method, the error does not occur, but then I get back to another problem I had originally, which I'm hoping that will be fixed if this problem is fixed.
I really hope that was clear enough. Thanks in advance!
You have a snippet with your javascript functions. Where does that code live? It it inside a class or function that could be getting called a second time? If so, var editorControl; could be getting run again and override your previous editorControl variable. I would put an alert right about var editorControl; to make sure.
alert( 'Should only happen once' );
var editorControl;
Since that didn't help, I guess you could try replacing
var tmp = editorControl.control.get_content();
with
tmp = document.getElementById(editorID);
in submitEditorPopup.
I have this following code, here CssClass is of the String type.
<asp:Panel ID="Panel1" runat="server" title="<%# Title %>" class="<%# CssClass %>">
<asp:Panel ID="Panel2" runat="server" Style="padding-top: 20px; color: Red">
Invalid Credential
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" Style="text-align: center; padding-top: 50px;">
<telerik:RadButton ID="LoginFaild" runat="server" Text="Ok" Font-Size="14px" Width="100px"
OnClientClicked='<%# "function(button, args){closeDialog(" + CssClass + ");}" %>' />
</asp:Panel>
Now I want to pass this String value to the JavaScript function closeDialog() which is:
var closeDialog = function (className) {
$("." + className).dialog("close");
}
When I am clicking on the button I am getting
loginError is not defined
in my Web Developer's Toolbar of Firefox.
How can I solve this problem?
Assuming that CssClass is set in c#, you do not need to specify the inline CssClass property in the close dialog constructor. Change your closeDialog function to:
var closeDialog = function () {
$("." + <%= CssClass %>).dialog("close");
}
Then your OnClientClicked event can be rewritten as:
OnClientClicked="function(button, args){ closeDialog(); };" or OnClientClicked="closeDialog();"
EDIT:
Script at the Top of the Page
var cssClass = '<%= CssClass %>';
Close Dialog Function
var closeDialog = function () {
$("." + cssClass).dialog("close");
}