update panel , add function that works after updating - asp.net

I use this jquery datepicker
I have input in the updatePanel
<input id="DateMask" type="text" />
and js code:
function SetD() {
alert(1);
}
$(document).ready(function () {
SetD();
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true
});
});
But the problem is that when i post my form to the server i only refresh update panel so $(document).ready(function () doesn't work after refreshing ,so where i can execute my function from?

You need to rebind in the Sys.WebForms.PageRequestManager.add_endRequest event.
See this similar post jQuery $(document).ready and UpdatePanels?

To make it work you need to re-initialize it after the updates of UpdatePanel. You can do that by using the UpdatePanel functions. I also like here to note, that you also need to unbind it just before the UpdatePanel updates to avoid memory leaks.
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the DatePicker
InitDatePicker();
});
function InitializeRequest(sender, args) {
// make unbind to avoid memory leaks.
$("#datepicker").unbind();
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the DatePicker
InitDatePicker();
}
function InitDatePicker()
{
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true
});
}
</script>
Almost the same question but on GridView: Asp.Net UpdatePanel in Gridview Jquery DatePicker

Related

Fire DropDownList SelectedIndexChanged event when using JQuery-UI Autocomplete

I'd like to post back to the server when my combobox changes value (ideally with an AJAX call in an update panel - but one thing at a time). I'm using the I'm using the jQuery UI AutoComplete Combobox and, unfortunately, it's interferring with the change event as I'm not changing the drop down list directly.
I'm using the implementation detailed here.
Here are some choice snippets
HTML Body Code
<span class="ui-widget">
<asp:DropDownList ID="cboLang" runat="server" AutoPostBack="True">
<asp:ListItem Value="ActionScript">ActionScript</asp:ListItem>
<asp:ListItem Value="AppleScript">AppleScript</asp:ListItem>
<asp:ListItem Value="Asp">Asp</asp:ListItem>
</asp:DropDownList>
</span>
Autocomplete Javascript
This is the autocomplete js that exexutes whenever a selection has been made. It will always run the function _removeIfInvalid
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
Server Side Code
Protected Sub cboLang_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles cboLang.SelectedIndexChanged
'DO OTHER STUFF HERE
Dim alert = String.Format("alert('{0}');", "Hi")
ScriptManager.RegisterStartupScript(Me, Me.GetType, "DropDownChange", alert, True)
End Sub
Generated Code
When an ASP.NET renders the page with the attached event, it produces the following code
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl00'];
if (!theForm) {
theForm = document.ctl00;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<select id="cboLang" onchange="javascript:setTimeout('__doPostBack(\'cboLang\',\'\')', 0)"
name="cboLang" style="display: none;">
Question
Where can I go about making changes to ensure that with each update to the autcomplete input, I can trigger a server event?
There are a couple things that are helpful for answering this question. One is to take a look at JQuery-UI's own documentation on this function:
// Initialize the autocomplete with the select callback specified:
$( ".selector" ).autocomplete({ select: function( event, ui ) {}});
// Bind an event listener to the autocompleteselect event:
$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} );
Essentially, what needs to happen, is something needs to signal a callback when the item has been selected (either from the menu or by typing and getting an exact match).
We can do this by modifying the default functionality demonstrated on the autocomplete page:
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
This code attaches listeneres on the select and change events and runs the inline defined function and the _removeIfInvalid function whenever those events fire (respectively)
By implementing the following changes we can do a postback when a valid selection has been made:
//attach listeners
this._on(this.input, {
autocompleteselect: "_selectFromMenu",
autocompletechange: "_removeIfInvalid"
});
Will get called anytime an item is selected from the menu:
_selectFromMenu: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('', '');
},
Will get called any time the text changes:
_removeIfInvalid: function (event, ui) {
// Selected an item, automatically valid, post back
if (ui.item) {
__doPostBack('', '');
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, post back
if (valid) {
__doPostBack('', '');
return;
}
// Remove invalid value...
Here's a jsfiddle with the complete code changes, although __doPostBack is commented out because it is not being handled by anything
A couple further note:
I'm calling __doPostBack, but I'm relying on that method being available because of asp.net event handling generated code.
In order to initialize the combo box, you have to call $("#combobox").combobox();. Make sure that whatever is preforming that operation is still getting called on the return from the post back, otherwise the functionality will not come back. This is one thing to work past if you're using the code asynchronously in an update panel.
Instead of __doPostBack(this.element.attr('name'), '');
write
if (this.element.attr('onchange') != undefined && this.element.attr('onchange').indexOf("__doPostBack") >= 0)
__doPostBack(this.element.attr('name'), '');

UpdatePanel PageRequestManager. Delay postback

I am trying to add some JQuery animations before and after every postback request is made inside my UpdatePanel. What I have so far is something like this:
<script type="text/javascript">
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
// End Request (1)
}
}
function BeginRequestHandler(sender, args) {
// Start Request (2)
}
$('.MyButtons').live('click', function () {
// Before request (3)
});
});
</script>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" CssClass="MyButtons"/>
</ContentTemplate>
</asp:UpdatePanel>
Let say I want to put some animation code at (3) that will be executed and then proceed with BeginRequestHandler function. How should I do that? Because right now the whole process executes 3,2,1 and I dn't know how to add that delay between steps 3 and 2. In other words I want to execute step 2 manually at step 3. Don't really want to use hidden buttons to do that.
Okay, I ended up using the following:
$('.MyButtons').live('click', function () {
var element = this;
$('#hideMe').hide('slow', function () {
__doPostBack(element.id.replace(/_/g, '$'), ''); // This will trigger a postback on a clicked server control
});
return false; // This will prevent asp.net click event on the server control
}

Hide and Show div's on Button Click in a UpdatePanel

I am using UpdatePanel ---> LinkButton --> Div --->Table Structure.
When I click the Linkbutton the div has to show the table format first and has to execute the code in its OnClick event, the problem I am facing is I've tried so many jquery functions shown below:
<asp:LinkButton ID="lnkbtnUnitAdd" runat="server" OnClientClick="Toggledivs()" OnClick="lnkbtnAdd_Click" Text="Add" ></asp:LinkButton>
Even if I used:
$(document).ready(function()
{
$("#lnkbtnUnitAdd").click(function () {
$("#divUnit").show("slow"); return false;
});
});
or
function Toggledivs()
{
$("#lnkbtnUnitAdd").click(function () {
$("#divUnit").show("slow"); return false;
});
}
or without using the OnClientClick property in LinkButton
the result is same, as the function is returning false in button Onclient click or document.ready function(), therefore buttons Onclick event is not firing.
And if I comment the return false, the div is not showing up properly.
Please help how to deal as the whole process is running in an updatepanel.
You might have to use Control.ClientID in this case. Try this
$(document).ready(function(){
$("#<%=lnkbtnUnitAdd.ClientID%>").click(function () {
$("#divUnit").show("slow"); return false;
});
});
I won't recommend adding the event handler in HTML. But the following code should work. You don't have to assign the click event again.
function Toggledivs()
{
$("#divUnit").show("slow");
return false;
}
Give
return true;
if you want the onclick function to get executed.
If I have understood what you meant, this should do it:
__doPostBack should be called only after the animation is done, you can do it by passing a callback function to jquery's show's, second parameter.
UPDATES:
$(document).ready(function()
{
$("#lnkbtnUnitAdd").click(function (e) {
var btnName = $(this).attr('name');
$("#divUnit").show("slow",function(){
__doPostBack(btnName,''); //now call the actual postback event
});
e.preventDefault(); //prevent default postback behavior
return false;
});
});

Will there be any issues when JQUERY Datepicker used with AJAX Update panel..?

i have used JQuery date picker in form- form contains just one text box and when we clicks on it--> it pops up the JQUERY datepicker.
In other web form in same project --> i have used script manager, Update panel and one textbox --> when click on it - am not getting JQUERY Datepicker Popped.??
What will be the issue.?? Any problem with-> async. postback triggers..?/
Will there be any issues when JQUERY Datepicker used with AJAX controls..??
Do you initialize the datepicker correctly on PanelUpdate ?
<script type="text/javascript">
$(document).ready(function() {
$(".clDate").datepicker();
});
</script>
Also for the update panel to fix again the DatePicker after the ajax update you need the foloowing code
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
$(".clDate").datepicker();
}
</script>
Update:About the Sys. -> http://msdn.microsoft.com/en-us/library/bb311028.aspx

Cufon.refresh after asp.net ajax refresh

I have a page which uses cufon and asp:UpdatePanel. After ajax callback the new content does not replace tags with cufon. I've tried:
<script type="text/javascript">
alert('Cufon refresh start!');
Cufon.refresh();
alert('Cufon must be ok!');
</script>
But don't get any alert or cufon replacement.
Related to How to have a javascript callback executed after an update panel postback? I've used pageLoad event which is triggered after each postback:
<script type="text/javascript">
function pageLoad(sender, args) {
Cufon.refresh();
}
</script>
I use the following
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
//rebind jquery here after update panel async postback!
InitSlider();
Cufon.refresh();
}

Resources