Jquery code on load not firing - asp.net

I have the following JQuery code in a external JS file linked into a
usercontrol in .Net 1.1 webapp.
The usercontrol is a timesheet.
When the page loads it calls MonthChange and works fine in one page.
But now I want to load the timesheet/usercontrol into aother
webpage that pops up a in a new browser window for printing.
Problem is my MonthChange is not firing.
Any ideas why???
$(function() {
MonthChange();
//TestData();
$('[class^=TSGridTB]').blur(function() {
var day = GetDay($(this).attr('id'));
var date = GetRowDate(day);
var bgcolor = GetInputFieldColor(date, false);
$(this).css("background-color", bgcolor);
$(this).parent().css("background-color", bgcolor);
//CalcHours($(this).get(0));
});
$('[class^=TSGridTB]').focus(function() {
var day = GetDay($(this).attr('id'));
var date = GetRowDate(day);
var bgcolor = GetInputFieldColor(date, true);
$(this).css("background-color", bgcolor);
$(this).parent().css("background-color", bgcolor);
});
$('[id$=lstMonth]').change(function() {
MonthChange();
});
});

without seeing further code, ensure that the selector is correct for the control in the new page.
The problem may be that the DOM has changed for the new page/window and JQuery does not yet know about it.
The change event
fires when a control loses the input
focus and its value has been modified
since gaining focus.
You might want to use the live event:
Binds a handler to an event (like
click) for all current - and future -
matched element.
When you bind a "live" event it will
bind to all current and future
elements on the page (using event
delegation). For example if you bound
a live click to all "li" elements on
the page then added another li at a
later time - that click event would
continue to work for the new element
(this is not the case with bind which
must be re-bound on all new elements).

Did you make sure that the new web page has jQuery script includes?

ensure you're using:
$(document).ready(
);
around your entire code block. The $ alone often does not do the trick.

Related

How to know which button of User Control is clicked from parent form Asp.net?

I want to capture which button is clicked in page load method of code behind file.
Button is user control button and It does not post back. Since it used by many other forms, I don't want to changes that button.
I tried this
Dim ButtonID As String = Request("btnRefresh.ID")
But it doesn't work.
Is it possible to know without touching in user control and using Javascript?
Thank you
As described here How to check whether ASP.NET button is clicked or not on page load:
The method: Request.Params.Get("__EVENTTARGET"); will work for
CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work
for Button controls such as Buttons and ImageButtons
But you have a workaround, first of all you have to define a hidden field in the Parent Page. In this field you will store which button inside the user control was clicked using javascript/jquery. And then in your Parent Page Page_Load method you just read the hiddenField.Value property:
JQuery
1) Add listener to every input type submit button:
$(document).ready(function () {
$("input[type=\"submit\"]").on("click", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
2) [Better one] Add listener to some indentificable div inside the user control and delegate the event to child inputs like this:
$(document).ready(function () {
$("#someElementOfUserControl").on("click", "input[type=\"submit\"]", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
Javascript
Since everything done with JQuery can be done with Javascript you can do the following (i will not write both samples, just one):
function handleClick(event) {
alert(event.target.name);
document.getElementById("hiddenField1").value = event.target.name;
}
var inputsInUC = document.getElementsByTagName('input');
for (i = 0; i < inputsInUC.length; i++) {
inputsInUC[i].addEventListener('click', handleClick, false);
}
Remember to define this javascript after all your html elements.
EDIT:
Also, for the completeness of the answer let me tell you that the proper way in case you can change the user control behaviour is to use events as described here How do i raise an event in a usercontrol and catch it in mainpage?

ASP GridView to be updated automatically when ModalDialog is closed

I have a gridView with search and filtering options, it is listing document from SharePoint Library, when i click on the Document name i added a Modal popup to display Documents properties page, if i update Document's title for example and select save, the item is updated but the gridview is still showing the old title, i need to press Search again in order to refresh the values.
the code i use for model popup is:
<script type="text/javascript">
function openModal(url) {
var options = SP.UI.$create_DialogOptions();
options.url = url;
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
// Dialog callback
function CloseCallback(result, target) {
if (result === SP.UI.DialogResult.OK) {
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
}
</script>
what should i do to refresh and bid gridview data when the popup is closed?
on the click of save button, make a serverside call to rebind the gridview. i.e
$(document).ready(function(){
$('id_of_save_button').click(function(){
//ajax call of serverside method to rebind the grid.
});
});
However with asp.net these things become little easy if you use modalPopupExtender that ships with asp.net
Hi for handling sharepoint save event using javascript u can use this function
function PreSaveAction()
{
// write your gride view data bind code
}

ASP.NET postbacks lose the hash in the URL

On an ASP.NET page with a tabstrip, I'm using the hash code in the URL to keep track of what tab I'm on (using the BBQ jQuery plugin). For example:
http://mysite.com/foo/home#tab=budget
Unfortunately, I've just realized that there are a couple of places on the page where I'm using an old-fashioned ASP.NET postback to do stuff, and when the postback is complete, the hash is gone:
http://mysite.com/foo/home
... so I'm whisked away to a different tab. No good.
This is a webforms site (not MVC) using .NET 4.0. As you can see, though, I am using URL routing.
Is there a way to tell ASP.NET to keep the hash in the URL following a postback?
The problem is that the postback goes to the url of the current page, which is set in the action of the form on the page. By default this url is without #hash in asp.net, and its automatically set by asp.net, you have no control over it.
You could add the #hash to the forms action attribute with javascript:
document.getElementById("aspnetForm").action += location.hash
or, if updating an action with a hash already in it:
var form = document.getElementById("aspnetForm");
form.action = form.action.split('#')[0] + location.hash
just make sure you execute this code on window.load and you target the right ID
I tried to put the code from Willem's answer into a JS function that got called everytime a new tab was activated. This didn't work because it kept appending an additional #hash part to the URL every time I switched tabs.
My URL ended up looking like http://myurl.example.com/home#tab1#tab2#tab3#tab2 (etc.)
I modified the code slightly to remove any existing #hash component from the URL in the <form> element's action attribute, before appending on the new one. It also uses jQuery to find the element.
$('.nav-tabs a').on('shown', function (e) {
// ensure the browser URL properly reflects the active Tab
window.location.hash = e.target.hash;
// ensure ASP.NET postback comes back to correct tab
var aspnetForm = $('#aspnetForm')[0];
if (aspnetForm.action.indexOf('#') >= 0) {
aspnetForm.action = aspnetForm.action.substr(0, aspnetForm.action.indexOf('#'));
}
aspnetForm.action += e.target.hash;
});
Hope this helps someone!
I have another solution, implemented and tested with chrome, IE and safari.
I am using the "localStorage" object and it suppose to work all the browsers which support localStorage.
On the click event of tab, I am storing the currentTab value to local storage.
$(document).ready(function() {
jQuery('.ctabs .ctab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage["currentTab"] = currentAttrValue;
// Show/Hide Tabs
jQuery('.ctabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
if (localStorage["currentTab"]) {
// Show/Hide Tabs
jQuery('.ctabs ' + localStorage["currentTab"]).show().siblings().hide();
// Change/remove current tab to active
jQuery('.ctabs .ctab-links a[href$="' + localStorage["currentTab"] + '"]').parent('li').addClass('active').siblings().removeClass('active');
}
});

How can I execute JavaScript from my code-behind after my UpdatePanel has finished loading its DOM elements?

I have an UpdatePanel with a repeater in it that is re-bound after a user adds an item to it via a modal popup.
When they click the button to add a new row to the repeater the code-behind looks something like this:
protected void lbtnAddOption_Click(object sender, EventArgs e)
{
SelectedOption = new Option()
{
Account = txtAddOptionAccountNumber.Text,
Margin = chkAddOptionMargin.Checked,
Symbol = txtAddOptionSymbol.Text,
Usymbol = txtAddOptionUsymbol.Text,
};
Presenter.OnAddOption(); // Insert the new item
RefreshOptions(); // Pull down and re-bind all the items
mpeAddOptionDialog.Hide(); // Hide the modal
// ... Make call to jQuery scrollTo() method here?
}
This works fine and the new row will show up quickly via the UpdatePanel.
However, there are often hundreds of rows and where the new one is added is based on the current sorting column used.
So, I wanted to take this as a chance to use the sweet jQuery ScrollTo plugin. I know that if I give it the ID of my overflowed container div and the ID of an element within it, it will smoothly scroll straight to the users newly added row.
However, there are two problems:
I need to find the appropriate row so I can snag the ClientID for it.
I need to execute the jQuery snippet from my code-behind that will cause my newly updated repeater to scroll to the right row.
I've solved #1. I have a reliable method that will produce the newly added row's ClientID.
However, problem #2 is proving to be tricky. I know I can just call ScriptManager.RegisterStartupScript() form my code-behind and it will execute the JavaScript on my page.
The problem I'm having is that it seems that it is executing that piece of JavaScript before (I'm guessing) the newly refreshed DOM elements have fully loaded. So, even though I am passing in the appropriate jQuery line to scroll to the element I want, it is erroring out for me because it can't find that element yet.
Here is the line I'm using at the end of the method I posted above:
string clientID = getClientIdOfNewRow();
ScriptManager.RegisterStartupScript(this, typeof(Page), "ScrollScript", String.Format("$(\"#optionContainer\").scrollTo(\"{0}\", 800);", clientID), true);
What do I need to do so I can ensure that this line of JavaScript isn't called until the page with the UpdatePanel is truly ready?
If the stuff you need to process is in the update panel, then you need to run your JS once that panel is loaded. I use add_endRequest for that. This below is hacked from something rather more complex. It runs once on document ready, but installs the "end ajax" handler which is triggered every time your update panel is updated. And by the time it fires, it's all there for you.
var prm = Sys.WebForms.PageRequestManager.getInstance();
jQuery(document).ready(function () {
prm.add_endRequest(EndRequestHandler);
});
function EndRequestHandler(sender, args) {
// do whatever you need to do with the stuff in the update panel.
}
Obviously you can inject that from code-behind if you want.
You can use the Sys.Application.load event which is raised after all scripts have been loaded and the objects in the application have been created and initialized.
So your code would be:
string clientID = getClientIdOfNewRow();
ScriptManager.RegisterStartupScript(this, typeof(Page)
,"ScrollScript"
,String.Format("Sys.Application.add_load(function(){{$(\"#optionContainer\").scrollTo(\"{0}\", 800);}});"
, clientID)
, true);

Active Index is not being persisted in jQuery accordion change event

I have an asp.net aspx page and on that page I have a hidden input field with and id of paneIndex. However, when I load the page, the alert shows index 1 which is correct on the first load, but if I open up pane 3 for example, the alert shows 1 still. Am I doing something wrong?
In a Custom.js file, I have the following code:
$(document).ready(function() {
$("#accordion").accordion({
active: 1,
collapsible: true,
autoHeight: false,
change: function(event, ui) {
var activeIndex = $("#accordion").accordion('option', 'active');
$("#paneIndex").val(activeIndex);
//alert(activeIndex);
}
});
});
In my server side button click, I have the following code:
string activeIndex = Request.Form["paneIndex"];
string script = string.Format(#"<script type=""text/javascript"">var paneIndex =
{0};</script>", activeIndex);
if(!ClientScript.IsStartupScriptRegistered("JSScript"))
ClientScript.RegisterStartupScript(this.GetType(),"JSScript", script);
I have just tested the jquery script locally here and it works fine for me without form submission / postback.
Therefore I assume your issue is related to the form submission / activeIndex variable not being set correctly.
If you use asp.net, do you need to submit the form instead of using postbacks?
I always try to do a postback to the server if possible instead of form submission.
If you use Visual Studio you could also try to set a breakpoint on the server-side code and investigate the Request.Forms collection contains the correct variables after submission.

Resources