My javascript code modifies some properties, visibility included. After postback, some properties stuck, others are "forgotten". Here I try to change the Text property of a textbox and the visibility property of a label to 'hidden'. After postback, the text is preserved, but the label is shown. I would very much like to keep the label hidden after the postback. The same occurs with the 'display' CSS property. Or, if I try to hide a <div>. Any help would be very much appreciated:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ShowHide.aspx.cs" Inherits="WebApplication1.ShowHide" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function ShowHide()
{
debugger;
var txt = document.getElementById('txtNumber');
txt.value='4';
var lbl = document.getElementById('lblShowHide');
if(lbl.style.visibility == 'hidden')
{
lbl.style.visibility = '';
}
else
{
lbl.style.visibility = 'hidden';
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblNumber" runat="server" Text="Enter Number" />
<asp:TextBox ID="txtNumber" runat="server" Text="5" />
<asp:Label ID="lblShowHide" runat="server" Text="Show" />
<input id="btnChangeByJS" type="button" value="HTML Change by JavaScript" onclick="ShowHide();" />
<asp:Button ID="cmdSubmit" runat="server" Text="ASP Submit" />
<asp:HiddenField ID="hfShowHide" runat="server" />
</div>
</form>
</body>
</html>
Thank you!
A postback is just another way of saying the html form was submitted. When you submit a form, the only things sent to the server are the value and name properties of the input and select elements in the form. That's why your "text" is preserved: it's the value attribute of that element. If you want to also preserve your visibility changes, or any other changes, you need to add an element to your form that can hold these changes somehow in it's value attribute.
That's essentially what ViewState is; an extra hidden element whose value property holds the current state of controls. But ViewState works for maintaining state between server instances of your page. It's not for moving new changes from the client to the server.
Hook on the client side pageLoad event and hide the text box there. Example:
function pageLoad() {
var txt = document.getElementById('txtNumber');
txt.value='4';
var lbl = document.getElementById('lblShowHide');
if(lbl.style.visibility == 'hidden')
{
lbl.style.visibility = '';
}
else
{
lbl.style.visibility = 'hidden';
}
}
Related
I'm trying to reset my form using javascript on client side. The code looks like this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" >
function Reset() {
TextBox1.text = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Reset()" />
</div>
</form>
</body>
</html>
This of course isn't working, I get the error that Button1 is undefinded. I tried looking control's name within browser (by viewing page source) and using that instead of its ID but that didn't work either.
you need to get the value using getElementById
var mybutton= document.getElementById('Button1');
mybutton.value = ""
I advise you to use jQuery for your javascript code. It's a standard anyway.
After you reference jQuery, you may rewrite your JavaScript as follows:
<script type="text/javascript" >
function resetForm() {
$("#<%=TextBox1.ClientID %>").val("");
}
</script>
If you still do not want to use jQuery, then you need to access your element using its client ID like following:
<script type="text/javascript" >
function resetForm() {
document.getElemenyById("<%=TextBox1.ClientID %>").value = "";
}
</script>
Also, as #Jon pointed out, you need to either rename your OnClientClick value to resetForm() or rename your JavaScript function.
I have some links in an UpdatePanel. For example:
Products
I also have a CSS rule that puts an icon next to off-site links (those that have an HREF that starts with "http"):
a[href^="http"]
{
padding-right: 18px;
background: transparent url("Icons/offsiteLink.png") no-repeat right bottom;
}
When the page loads initailly, the links correctly do not have the off-site icon. The problem is that after an Ajax postback using the UpdatePanel, the icon appears next to the links! I added a hover event to display the href attribute, and it has indeed been changed to have the full path to the page after the Ajax postback. It doesn't matter if the links are plain HTML tags or a TreeView node.
Is this an issue with ASP.NET, or Ajax in general? Can I stop it?
Thanks.
Update:
I have created a brand new Web Site project. This is in Visual Studio 2008/.NET 3.5. Here is the entirety of the code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="mainScriptManager" runat="server" />
<asp:UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<p><a id="internalLink" href="About.aspx"
onmouseover="$('#hrefValue').text($(this).attr('href'));">About</a></p>
<p><a id="offsiteLink" href="http://example.com/"
onmouseover="$('#hrefValue').text($(this).attr('href'));">Offsite</a></p>
<p>HREF: <span id="hrefValue"></span></p>
<asp:Button ID="submitButton" Text="Post Back" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
(The code behind is empty.)
When I load the page in IE 7 and hover the links, I get:
About.aspx
http://example.com/
Then, I click the button, and hover the links again. This time they are:
http://localhost:4069/TestSite/About.aspx
http://example.com/
Notice that the first one changed to the full path.
Instead of looking for "http", you could add a rel="external" attribute to external site links, then style them using:
a[rel=external] {
}
See CSS - style a link based on its "rel" attribute?
It turns out that this was caused by an issue with IE7. IE8 no longer has the issue.
Due to several factors, I decided to use JavaScript to fix it. Here is that code. I also included a snarky comment about my company still targeting IE7 ;)
company.offsiteIconFix = (function() {
function init() {
var i, allAnchors = document.getElementsByTagName("a");
for (i = 0; i < allAnchors.length; i++) {
if (allAnchors[i].hostname && allAnchors[i].hostname ===
location.hostname) {
var trimIndex = allAnchors[i].href.indexOf(allAnchors[i].host) +
allAnchors[i].host.length;
var trimmedUrl = allAnchors[i].href.substring(trimIndex);
allAnchors[i].setAttribute("href", trimmedUrl);
}
}
}
return {
init: init
};
})();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(company.offsiteIconFix.init);
I could change it to insert "rel=external" as suggested by mgnoonan.
Here's what I have so far but thing aren't really working. (I dragged the jQuery.js file from the Solution Explorer to the area of my html.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SignUpFormTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//fade in the context of whatever is inside the div tag.
$('#name').fadeIn("slow");
});
</script>
</head>
<body bgcolor="#FFFFFF">
<p>
Note that this form doesn't actually do anything
except illustrate the Required Field Validator.
</p>
<form id="frmValidator" action="required.aspx" method="post" runat="server">
Enter Your Name:
<asp:TextBox id="txtName" runat="server" />
<div id="name"><asp:RequiredFieldValidator id="valTxtName" ControlToValidate="txtName" ErrorMessage='<img src="../Images/no.png">' runat="server" /></div>
<br />
<asp:button id="btnSubmit" text="Submit" runat="server" />
</form>
<p>
Hint: Try submitting it before you enter something.
</p>
</body>
</html>
When validating the icon just pops up.
No fade in or anything. Also, I know my current solution is hacky, so I'd really like someone to tell me what I should do instead of a creating a DIV tag just for the purpose of one animation.
Make sure the reference to JQuery is valid and use this code:
$(document).ready(function() {
$('#name').hide().fadeIn("slow");
});
If I'm not mistaken, since the div is already visible in your case, jQuery will not fade it in. The hide() method ensures that the div is initially not visible and then fades in slowly.
$(document).ready(function() {
document.getElementById('valTxtName').onpropertychange = function(){
$('#name').fadeIn("slow");
}
});
I have a multiline textbox that by default, is set to ReadOnly. I would like a button on the page to change the control to allow it to be edited. I would like this code to run on the client side because the page renders slowly and I'd like to avoid the post back.
The problem I'm having is the javascript code that I wrote to remove the readonly attribute appears to have no effect. I posted a stripped down example that illustrates the problem for your review.
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script type="text/javascript" language="javascript">
function EnableEditing() {
var e = document.getElementById("<%=TextBox1.ClientID%>");
var result = e.removeAttribute("readonly");
alert(result);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div> </div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True" TextMode="MultiLine">test</asp:TextBox>
<input id="Button1" onclick="EnableEditing()" type="button" value="Remove RO" />
</form>
</body>
</html>
TextBox1 is the server side id,
try
var e = document.getElementById("<%=TextBox1.ClientID%>");
var result = e.removeAttribute("readonly",0);
or if you dont want the caseinsensitive search
var result = e.removeAttribute("readOnly");//note upercase Only
Use var e = document.getElementById("<%=TextBox1.ClientID%>");
Also, if you want to read the modified text on postback, you can't set the readonly attribute on the server control. You have to set it on the client only, as in: TextBox1.Attributes("readOnly") = "readOnly";
Is SearchString acting as property of Page class?
Here is code,
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public string SearchString
{
get { return txtSearch.Text; }
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Button Search Typed</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblSearch"
Text="Search:"
Runat="server" />
<asp:TextBox
id="txtSearch"
Runat="server" />
<asp:Button
id="btnSearch"
Text="Go!"
PostBackUrl="ButtonSearchResultsTyped.aspx"
Runat="server" />
</div>
</form>
</body>
</html>
It is a property of your page class. This is not the page class. Your class inherits from the main page class.
Also, you need to be careful how you use thist kind of thing. Remember, ASP.Net pages are stateless, just like with other platforms. That means every time you do a postback, including just to handle simple server events like button clicks, you are working with a new instance of the class. Any previous SearchString value was lost.
It's a property of the class generated for your ASPX file, which inherits from System.Web.UI.Page. It's not added to that class itself, of course.