JQuery scrolling issue when submiting a form - asp.net

I'm building an ASP.NET website and I'm puzzled with the behavior of one page, I've got a long form and a submit button, I've got the piece of javascript below in the page to handle scrolling the page back up upon submiting the form, the first time I click the submit button it works all the sequent clicks don't work at all, any idea why?
<script type="text/javascript">
$(".thebutton").click(function(){
$("html, body").animate({scrollTop: 200}, 1000);
});
</script>
Cheers,
Thi

Ahh,
Using an Ajax post makes this different that my post above.
Does your ajax call change the buttons on the page? I assume you are using an UpdatePanel with the buttons in qustion in it.
Since when you make the Ajax call, the controls in the UpdatePanel are being rebuilt, the DOM is seeing them as different objects and these new objects are no longer bound to the jQuery click function. You will need to re-bind these buttons click event after the ajax post to re-enable the functionality you are looking for.
Using jQuerys new "Live" Handlers should do the trick for you:
$(".thebutton").live("click", function() {
$("html, body").animate({scrollTop: 200}, 1000);
});
Hope it helps.

If your Submit button performs a full postback, I would view source on the second web page instance, and make sure that the script is still there.

Your script will run BEFORE the Post.
Imagine if you will:
Initial Page Load
Bind Click event with jQuery
Click Button
jQuery Click is raised
html and body scrollTop are set to 200
during the "animate" the form is submitted
asp.net back end click event code is run
page is reloaded.
string script = "$(function() { $('html, body').scrollTop(200); });";
ClientScript.RegisterStartupScript(this.GetType(), "scrollTop", script, true);
That should take care of what you want to accomplish.
Hope it helps.

Related

ASP.NET / VB.NET: Reference a Textbox value without postback?

I have a child aspx page in an iFrame. There are a few textboxes, which are populated in the page load event.
There is also a LinkButton which the user clicks when s/he is finished editing the fields. There are some javascript functions and other things going on, so a full postback (ie: asp button) is out of the question.
Problem is, I need to reference the textboxes NEW values (user changes) after the linkbutton is clicked.
Is there any way to do this?
Thanks,
Jason
EDIT:
After playing with the interface a bit further, I realized the Page_Load event was firing as soon as the LinkButton was clicked. Of course this is where the data is initially loaded, so any changes the user made is immediately written over. Current plan of attack is to create an IsLoaded cookie value and check if true before the mentioned code executes. If anybody has a better idea, please let me know!
Thanks,
Jason
You can use jQuery to grab the textbox value on click of the button.
<script type="text/javascript">
$(document).ready(function() {
$('.btnSubmit').click(function(e) {
alert($("#txtName").val());
});
});
Then you may pass this textbox value to a server side method by calling it using jQuery AJAX. See the link below .
http://weblogs.asp.net/karan/archive/2010/09/12/calling-server-side-method-using-jquery-ajax.aspx
You want to access the new textbox values from the parent or from within iframe which has that webform opened?

JQuery Date Picker issue inside Update Panel

i am using this Sys.WebForms.PageRequestManager.getInstance().add_endRequest(addDataPicker); for my script to load on every post back for JQuery Datepicker. Because i am using updatepanel. Its working fine in second postback.but its not working the first time of page load. Please Help me out
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(addDataPicker) event is raised after an asynchronous postback is finished and control has been returned to the browser.So your addDataPicker is added after postback is done, you need to add this after document is loaded, i.e. if you are using Jquery this can be done by,
$(document).ready(function() {
// put all your datepicker init function here.
});
Hope this will help.

jQueryUI dialog, gridview and updatepanel

I'm using jQuery to convert a column of hyperlinks within a gridview into UI dialogs.
This gridview is in an updatepanel, and for one of the dialog's buttons I perform a __dopostback on this updatepanel, which refreshes the changes I've made within the dialog.
It all works rather nicely, apart from one small issue.... that is when the updatepanel posts back and recreates the gridview table with new data.. I lose the dialog functionality!
Previously, I simply had the following:
$('a.createdialog').click(function(e) { <iframe code here>.dialog( { <buttons and other options> } )
and it made sense that, once the gridview was updated, the above will essentially be wiped.
So I put that code into a function, and as well as running this function on the page load I also placed the function into the dialog's button code. This however does not fix the issue... I tried moving where I call this function around from the button to the updatepanel's loading events with registerstartupscript().. again no luck.
any ideas?
Cheers :D
Try the live method, description from JQuery Docs: Attach a handler to the event for all elements which match the current selector, now and in the future. The async postback/refresh is killing the handler; live can help in this situation persist the handler.
http://api.jquery.com/live/
$('.clickme').live('click', function() {
// Live handler called.
});
HTH.

how to get javascript to execute in update panel

I have an update panel which contains a table, to which I add rows of controls on a button click. One of the controls that is added, is a user control and it is a datepicker. Inside of that user control I have a textbox, and I have JQuery which applies the JQuery UI DatePicker plugin to it thereby turning it into a datepicker. It's not a problem if that user control is loaded onto a page dynamically, however, if it is done on async postbacks inside an update panel, the javascript doesn't fire and therefore the textbox is render but without all the jquery datepicker functionality. Here's some code that's inside the DatePicker.ascx:
$(function() {
//reset the localization
$.datepicker.setDefaults($.extend($.datepicker.regional['']));
$("#<%=txtDate.ClientID%>").datepicker({ dateFormat: 'mm/dd/yy', showOn: 'button', buttonImage: '/images/calendar.gif', buttonImageOnly: true, altField: '#<%=txtDate.ClientID%>' });
}
So this jquery isn't fired when the control is loaded in dynamically on an async postback. So how can I make this work?
Check this Page
look for the session on DatePicker
it says that ASP.NET AJAX UpdatePanel's wipes the DOM, so the load doesn't fire.
the post says you can either, use the EndRequest handler, or the pageLoad shortcut, however I'm thinking if you just couldn't register the javascript with ScriptManager.
Hope this helps.
When you render a script in a response, it does just that: render the script. It is during the rendering of the page that the script is first rendered, and that has already happened by the time that this code is being executed.
Microsoft has come up with a solution for this, which is to register the script block via ScriptManager.RegisterClientScriptBlock, and the ScriptManager will then see to it that the script is executed after page load.
Depending on your situation, that may or may not be helpful. Or, in the intermediate: it may be helpful only with a bit of workarounds. From your comment, I can think of one workaround I might have considered using:
Add a GetClientScript method to your UserControl, where the JavaScript is returned. If the UserControl is loaded on a regular page load, you invoke that method at the point where you are currently rendering your script. If the control is loaded in a UpdatePanel postback, you get the scriptbody from the control using that method, and register it in the ScriptManager at hand. You should, in this case, also pass a parameter back to the UserControl not to register the script once more, where it usually does.
Is the the DatePicker.ascx inserting that javascript at the top of the page during the initial load? And then that function fails since the datepicker is not loaded yet. And then you load the datepicker on async into the update panel, but the function is not called.

How do I bind my Jquery function to a asp.net button and still allow Validation and PostBack?

Now I could be going about this the wrong way so if there is a better solution please post that as well. What I am trying to do is disable a button once it is clicked to prevent double clicks. In the past I have done my just disabling the button onclick but with webforms I am running into a little bit of a snag because there is validation on the page so I need that to fire and I need to post back.
So I have the following JQuery function to make a button disable itself on click. Here is the JQuery:
jQuery.fn.disableOnClick =
function()
{
return this.each(function()
{
$(this).click(function()
{
$(this).attr('disabled', 'disabled');
return true;
})
})
};
Intended usage would be:
$(document).ready(function()
{
$("#<%= btnSomeButton.ClientID %>").disableOnClick ();
});
This doesn't work... the button always disables, the validation is ignored and the postback doesn't even happen. I would assume because I am overwrittin the click handler. Suggestions?
UPDATE: I have tried just a basic function that is connected to the 'OnClientClick' of the button to do:
// In my Page_Load
btnSomeButton.OnClientClick = "return DisableButton('" + btnSomeButton.ClientID + "');";
// Javascript function
function DisableButton(id)
{
var bButton = $("#" + id);
if (Page_ClientValidate())
{
$("#" + id).attr('disabled', 'disabled');
__doPostBack(id, '');
}
}
This works as expected in a non master page setup but when I try to use it with a page that has a master page, the postback occurs and the Page_Load fires but the button click handler never gets called. It's like the __doPostBack is not sending which control event to fire correctly.
Any suggestions for changes or even a whole different approach?
One idea for a different approach (disclaimer: this is not a fully baked solution) is to go from the submit action of the form instead of the click handler of the button.
The validation all happens through the submit handler of the form. If everything checks out, the form is allowed to submit. If you could hook into that process, then when the form started to submit for real, you could find all buttons with the class DisableOnSubmit and disable them.
Validation could take some time, however, and some people (annoyingly) seem to like to double-click on web forms, so it might be best to blend the approaches. Disable the button immediately with a click handler, then if validation fails, re-enable the buttons that were disabled.
EDIT In response to comments
This description could be turned to be more like the signature in the question (where any button could be made to be click-once regardless of its CSS classes).
Create a jQuery extender where the buttons that fit the selector are given an onClick handler and (if not already done) the hook is added to the validation being complete. The onClick handler adds the clicked button to a collection of "currently in click evaluation" buttons. If validation succeeds, the form submits normally. If validation fails, the buttons in the collection are re-enabled and removed from the collection.
For the evil update panels, you might want to look into specifying these events with live bindings (used to be a plugin, but I think it's now part of the jQuery core depending on which version you're using) so that the event handlers are reregistered when the partial postbacks complete.
I get the feeling you can use GetPostBackEventReference to do the actual postback once you've done your validation dance.
Edit Oops, forgot the other half of the answer :-)
As for the double postback, I've used Postback Ritalin by Dave Ward in the past to curtail those pesky hyperactive users.
Add this to your startup code (ready event handler):
var elemButton = $('#<%= Button1.ClientID %>');
var fnExistingHandler = elemButton[0].onclick;
elemButton[0].onclick = function()
{
fnExistingHandler();
if (!Page_BlockSubmit)
{
$(this)
.hide()
.after('<input type="button" value="Please Wait..." disabled="disabled" />');
}
};
Basically you append new code to existing click handler. Note checking global variable Page_BlockSubmit.
Instead of disabling submit button you can hide it and immediately insert disabled button in its place. Because this happens very quickly it will look as button becoming disabled to the user. Details are at the blog of Josh Stodola.
Edit: fixed client validation.
Haven't tried it but what about something like this:
$("input[type=submit]").live("click", function() {
$(this).hide().clone().insertAfter(this).show().attr("disabled", "disabled").val("Please wait...");
return true;
});
This will ensure a submit button isn't disabled which ASP.NET doesn't like.

Resources