Not sure what i am doing wrong here but I have a webpage which has a usercontrol wrapped in an update panel. This usercontrol has a gridview with a textbox in an ItemTemplate and a textbox in a footer template. The textbox in the footertemplate is supposed to get the calculated value from a function in jquery. Below is my script to get the total but the total doesn't get calculated. Please advise what am I doing wrong here. Also, let me know if I need to provide additional information. This script is in the master page. I tested to make sure jquery is working by putting the alert after the document ready which it works. Any help would be greatly appreciated.
<script language="javascript">
var totalQuantity = 0;
$(document).ready(function() {
//alert('This is test');
$(document).on('blur', 'input[id^="MainContent_MainContent_ucProjectionSet3_upProjections"]', function() {
alert('This is test');
totalQuantity = 0;
$('input[id^="MainContent_MainContent_ucProjectionSet3_gvProjections_txtCurrentTime_"]').each(function(index) {
doTotalCal($(this).attr("id"));
});
});
function doTotalCalc(_id) {
var indexVal = _id.Replace("MainContent_MainContent_ucProjectionSet3_gvProjections_txtCurrentTime_", "");
console.log(indexVal);
var strTotalQuantity = $('input[id^="MainContent_MainContent_ucProjectionSet3_gvProjections_txtCurrentTime_' + indexVal + '"]').val().replace("$", "");
totalQuantity += Number(strTotalQuantity);
}
$("#MainContent_MainContent_ucProjectionSet3_gvProjections_lblCurrentTimeTotal").html(totalQuantity);
});
</script>
I was able to accomplish this without using update panel. I didn't need to have an asynchronous postback for this project, so removing it was a fine option in making the jquery to work.
<script type="text/javascript">
$(document).ready(function() {
$("[id*=gvProjections]input[type=text][id*=txtCurrentTime]").keyup(function(e) {
GrossTotal();
});
});
var gross;
function GrossTotal() {
gross = 0;
$("[id*=gvProjections]input[type=text][id*=txtCurrentTime]").each(function(index, item) {
gross = gross + Number($(item).val());
});
$("[id*=gvProjections][id*=lblCurrentTimeTotal]").text(gross);
}
function isNumberDecimalKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 46) //decimal
return true
else if (charCode > 57 || (charCode > 31 && charCode < 48))
return false;
else
return true;
}
After a user clicks the log out button I have it take them to a redirection page which displays a message and says " Logging out and Redirecting in ? seconds." I am using
Response.AddHeader("REFRESH", "3;URL=Login.aspx");
is there a way to display how many seconds are left until they are redirected in label?
In your redirect page you need to use JavaScript to handle it.
This sample may help you: http://javascriptsource.com/navigation/countdown-redirect.html
Following up on my comment, you could accomplish your solution via the following code:
<script type="text/javascript">
var timeLeft = 3;
function decrementCounter() {
if (timeLeft > 0) {
document.all('countDown').innerHTML = "Redirecting in " + timeLeft + "...";
timeLeft--;
setTimeout("decrementCounter()", 1000);
}
else {
window.location = "http://www.google.com/"
}
}
</script>
<body>
<form>
<label id="countDown">3</label>
<input type="button" value="Display alert box in 3 seconds" onclick="decrementCounter()" />
</form>
</body>
For example ,
When you Click the Logout button , You can create a count down javascript by dynamic
protected void OnLogout(object sender, EventArgs e)
{
string url = "~/Login.aspx";
string msg = "Logging out and Redirecting in ? ";
StringBuilder js = new StringBuilder("<script language=\"javascript\">")
.Append("var ts = 3; setInterval(\"redirect()\",1000);")
.Append("function redirect(){ if(ts == 0){")
.Append("window.location.href=\"" + url + "\"; }else{")
.Append("document.body.innerHTML = \"msg \" + (ts--)+\"seconds\";}}")
.Append("</script>");
Response.Write(js.ToString());
}
You'll need to use a client-side technology, I.e. JavaScript. Using server-side will require calls to the server which is not needed for something simple like this.
Because you are using Microsoft aspx, you can create a label on the client side and implement an AJAX by giving your code-behind the Id of the label and changing its value base on the time left.
I have an ASP.net WebForms page that has a lot of content on the top of the screen. It has a link button that will post back to the page and show another section of the page. When the page refreshes, I would like to set focus and scroll down to this section of the page.
I tried doing
txtField.Focus()
in my code behind and it will set focus and try to scroll there, but then scrolls right back to the top. The focus is still on my text box but the position of the screen is at the very top. The Link is at the top of the screen which is causing the postback. I want to scroll to the very bottom of the screen. It does this briefly and then scrolls right back to the top.
I have tried setting
Page.MaintainScrollPositionOnPostback = false;
but that doesn't seem to help either.
Is there some way I can force it to go to a specific position?
Is it possible to add an anchor tag to the URL when I postback using a button or link button?
Page.MaintainScrollPositionOnPostBack = true; should take you back to the same position on the screen, but you could use AJAX, or you could use SetFocus() to focus on a specific control after the postback:
http://msdn.microsoft.com/en-us/library/ms178232.aspx
You can use the code below if you have an anchor for the location:
Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);
In your case I suggest you to keep the default value of Page.MaintainScrollPositionOnPostBack, and use the pure javascript scrolling function
function scrollToDiv()
{
document.getElementById('yourDiv').scrollIntoView();
}
And call it at the page startup with a little delay of 1ms (pure javascript again)
setTimeout(scrollToDiv, 1);
And finally call it from the C# code behind, with the RegisterStartupScript (js executed after all the page has been loaded) :
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ScrollToADiv", "setTimeout(scrollToDiv, 1);", true);
Like this, it will bypass any asp automatic scrolling
try this
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) {
string targetId = Page.Request.Params.Get("__EVENTTARGET");
Page.ClientScript.RegisterStartupScript(this.GetType(), "focusthis", "document.getElementById('" + targetId + "').focus()", true);
}
}
Page.MaintainScrollPositionOnPostback = true seems to work just fine.
I've tried Matthieu Charbonnier answer, but it didn't work unless I've added
" window.scrollTo = function () { };"
as it was suggested in http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html
I've created a helper method, that's working in Chrome,FireFox and IE
public static void ScrollToControl( Page page, string clientId, bool alignToTop)
{
//NOTE: if there are more than one call on the page, first one will take preference
//If we want that last will take preference, change key from MethodBase.GetCurrentMethod().Name to anchorName
//recommended in http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html
String script = " window.scrollTo = function () { };" + Environment.NewLine;
script += String.Format("document.getElementById('{0}').scrollIntoView({1});" , clientId, alignToTop.JSToString());
page.ClientScript.RegisterStartupScript(TypeForClientScript(), MethodBase.GetCurrentMethod().Name, script, true );
//return script;
}
public static string JSToString(this bool bValue)
{
return bValue.ToString().ToLower();
}
Use getElementById('{0}').scrollIntoView is simpler than location.hash , because you don't need to add extra anchor element.
Parameter alignToTop is very convenient to specify do you want to show control at the top or bottom of the screen.
I have
<asp:MultiView ID="mvAriza" runat="server">
<asp:View ID="View14" runat="server">
............ .......
</asp:View>
</asp:MultiView>
on *.aspx page. And on the *.aspx.cs page on a button click.
Page.SetFocus(mvAriza.ClientID);
It works great.
This scroll automatically to desired Div in asp.net Control
This is Function
call it from Where you Want
and also Download Java script file
OnClientClick="return scrollGrid()"
function scrollGrid1() {
$('html,body').animate
(
{
scrollTop: $('#Div1').offset().top
},
'slow'
)
}
While not elegant for your situation, it is also possible to use dummy Custom Validators, set the one you want to scroll to as invalid then do
DummyCustomValidator.SetFocusOnError = true;
In my case, I am actually using page Validators with async postbacks and multiple programmatically shown/hidden panels on a long vertical form. Since some fields are only required if MyLogicalParent.Visible = true and if specific answers are given in other controls, such as a RequiredFieldValidator on a TextBox when "Other" is selected in a CheckBoxList, I have a LOT of logic to process page validation. Setting scroll positions was painful in all of the normal methods.
I also use RegisterStartupScript to handle maintaining the current scroll position when async postbacks alter the page's vertical dimension.
<script type="text/javascript">
$(document).ready(function () {
var windowHeight = $(document)[0].documentElement.clientHeight; /*This is the height of the viewable browser area.*/
var scrolledPosition = $(window)[0].scrollY; /*This is the number of Pixels the Window is currently scrolled to.*/
var scroll = windowHeight + scrolledPosition; /*This should be the same as $(window).scrollTop() */
/*If the amount scrolled + the height of the window is Less than or equal to the total height of the page (past the viewable client window)*/
if ($(window).scrollTop() + getWindowSize()[1] <= getDocHeight()) {
/*Move the morescroll div to the bottom of the page... -34 is the height of the div plus a small bottom margin.*/
$("#morescroll").offset({ top: windowHeight - 34 });
}
})
/*This is the total height of the document including the area past the viewable client window.*/
function getDocHeight() {
var D = document;
/*The Largest of these six numbers is the total doc height. */
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
/*This is the width and height of the Viewable Browser area.*/
function getWindowSize() {
var myWidth = 0, myHeight = 0;
if (typeof (window.innerWidth) == 'number') {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return [myWidth, myHeight];
}
//This sets a transparent div <div id="morescroll" class="scrollMinder"> with the text "Scroll down for more." to the bottom of the viewable page.
$(window).scroll(
function () {
var windowHeight = $(document)[0].documentElement.clientHeight;
var scrolledPosition = $(window)[0].scrollY;
var scrll = windowHeight + scrolledPosition;
document.getElementById('<%= HF_LastScrolled.ClientID %>').value = scrolledPosition;
var docHeight = $(document)[0].documentElement.scrollHeight;
/*if we are scrolled to within 60 pixels from the bottom of the document, hide the indicator so it doesn't cover the footer.*/
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 60) {
$("#morescroll").hide();
}
/*if we scroll back above 60 pixels from the bottom of the document, show the indicator and set the top of the div to -34 pixels.*/
else if ($(window).scrollTop() + getWindowSize()[1] <= getDocHeight()) {
$("#morescroll").show();
$("#morescroll").offset({ top: scrll - 34 });
}
});
</script>
<%-- This stores the Y scroll location.--%>
<asp:HiddenField ID="HF_LastScrolled" runat="server" />
<div id="morescroll" class="scrollMinder">
<span class="spanMinder">Scroll down for more.</span>
</div>
private string LastScrolled = "";
protected void Page_PreRender (object sender, EventArgs e)
{
if (string.IsNullOrEmpty(LastScrolled))
{
LastScrolled = "0";
}
if (string.IsNullOrEmpty(scrollPosition))
{
sb.Clear();
sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
sb.AppendLine("function EndRequestHandler(sender, args) {");
sb.Append("scrollTo(0, ").Append(LastScrolled).Append(");");
sb.AppendLine("}");
sb.AppendLine("function load() {");
sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
sb.AppendLine("}");
cs.RegisterStartupScript(GetType(), "ScrollToLastPosition", sb.ToString(), true);
scrollPosition = "ScrollToLastPosition";
}
if (!string.IsNullOrEmpty(scrollPosition))
{
ScriptManager.RegisterStartupScript(this, GetType(), scrollPosition, sb.ToString(), true);
}
}
protected void Page_Load (object sender, EventArgs e)
{
LastScrolled = HF_LastScrolled.Value;
Page.MaintainScrollPositionOnPostBack = false;
}
protected void SetScrollToLastPosition ()
{
sb.Clear();
sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
sb.AppendLine("function EndRequestHandler(sender, args) {");
sb.Append("scrollTo(0, ").Append(LastScrolled).AppendLine(");");
sb.AppendLine("}");
sb.AppendLine("function load() {");
sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
sb.AppendLine("}");
cs.RegisterStartupScript(GetType(), "ScrollToLastPosition", sb.ToString(), true);
scrollPosition = "ScrollToLastPosition";
string tempstring = sb.ToString();
ScriptManager.RegisterStartupScript(this, GetType(), scrollPosition, sb.ToString(), true);
}
protected void SetScrolltoPositionY (int y)
{
sb.Clear();
sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
sb.AppendLine("function EndRequestHandler(sender, args) {");
sb.Append("scrollTo(0, ").Append(y).AppendLine(");");
sb.AppendLine("}");
sb.AppendLine("function load() {");
sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
sb.AppendLine("}");
cs.RegisterStartupScript(GetType(), "ScrollTo-0-" + y.ToString(), sb.ToString(), true);
scrollPosition = "ScrollTo - 0-" + y.ToString();
string tempstring = sb.ToString();
ScriptManager.RegisterStartupScript(this, GetType(), scrollPosition, sb.ToString(), true);
}
I am using a treeview control. I am buliding the tree dynamically. sometimes the tree becomes larger and the down scroll bar is need to see the entire tree.
user can select a node from the tree. if one node is selected ,i change the color of the node from server side.
my problem is that if a user selected a node which is bottom in the tree(means, the user used the down scrollbar to see that node), after postback it shows the top of the tree.to see the selected node the user need to use the down scroll bar.
I need to show the selected node after postback. How can I do this?
I am using c# and asp.net
With help of jquery we can send the selected node id to the query string and on document.ready we can read back and highlight that node.
Have a look on the code:
Code behind onclick code:
public void TreeView1_OnClick(Object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(
Page,
Page.GetType(),
"HighlightSelectedNode",
"HighlightSelectedNode();",
true
);
}
and the javascript:
<script type="text/javascript" language="javascript">
function HighlightSelectedNode() {
var selectedNodeID = $('#<%= TreeView1.ClientID %>_SelectedNode').val();
if (selectedNodeID != "") {
document.location.href = "http://" + window.location.host
+ window.location.pathname
+ "?Node=" + selectedNodeID;
return false;
} else {
// alert("Not found");
}
}
// Highlight active node on pageload.
$(document).ready(function () {
var querystring = location.search.replace('?', '').split('&');
var queryObj = {};
for (var i = 0; i < querystring.length; i++) {
var name = querystring[i].split('=')[0];
var value = querystring[i].split('=')[1];
queryObj[name] = value;
}
var nodeID = queryObj["Node"];
$('#' + nodeID).css({ 'background-color': '#888'});
});
</script>
You can use update panel to work around this issue.
I have masterpage with content place holder. i have contentpage which is using master page . in all my content page i need to default focus on the text box so that the user can directly type in text box instead moving the mouse over the textbox. in some page there is no text box so that i donnot nnet keep default focus over there
Is there any way i can do it in my master page once and can reuse that in all my content page
thank you
try using this...
((TextBox)Master.FindControl("txtRequiredFocus")).Focus();
You could include this in your master page's load event:
// if the ID is constant you can use this:
/*TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.FindControl("myTextBox");
*/
// this will look for the 1st textbox without hardcoding the ID
TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.Controls.OfType<TextBox>()
.FirstOrDefault();
if (textBox != null)
{
textBox.Focus();
}
This would match up with a content page that has the following markup:
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
</asp:Content>
EDIT: if LINQ isn't an option then you can use this instead:
foreach (Control control in Page.Controls[0].FindControl("ContentPlaceHolder1").Controls)
{
if (control is TextBox)
{
((TextBox)control).Focus();
break;
}
}
Indiscriminate JavaScript approach to selecting the first valid input field on a page:
function SelectFirstInput() {
var bFound = false;
for (f = 0; f < document.forms.length; f++) {
// for each element in each form
for (i = 0; i < document.forms[f].length; i++) {
// if it's not a hidden element
if (document.forms[f][i].type != "hidden") {
// and it's not disabled
if (document.forms[f][i].disabled != true) {
// set the focus to it
document.forms[f][i].focus();
var bFound = true;
}
}
// if found in this element, stop looking
if (bFound == true)
break;
}
// if found in this form, stop looking
if (bFound == true)
break;
}
}
<script language="javascript" type="text/javascript" >
window.onload=function(){
var t= document.getElementById('<%=TextBox1.clientID %>');
t.focus();
}
</script>
If you use jQuery, a possible solution is:
Give the textbox you want to set focus to a special class. "focus" works well for this purpose.
Write code such as the following in your master page or included by your master page in a js script file:
$(document).ready
(
function()
{
//get an array of DOM elements matching the input.focus selector
var focusElements = $("input.focus").get();
//if a focus element exists
if(focusElements.length > 0)
{
focusElements[0].focus();
}
}
);
A similar approach using vanilla JavaScript would be to tag the textbox with a special attribute. Let's use focus.
window.onload = function()
{
//get all input elements
var inputElements = document.getElementsByTagName("input");
var elementToFocus = null;
for(var i = 0; i < inputElements.length; ++i)
{
var focusAttribute = inputElements[i].getAttribute("focus");
if(focusAttribute)
{
elementToFocus = inputElements[i];
break;
}
}
if(elementToFocus)
{
elementToFocus.focus();
}
};
Control masterC =
Page.Master.FindControl("ContentPlaceHolder1");
TextBox TextBox1 =
masterC.FindControl("TextBoxUsername") as TextBox;
TextBox1.Focus();