How to excecute Javascript after failed form validation - javascript

I am using ASP.NET 3.5, and the jquery.hint.js plugin. It works great, with one small problem. I have various ASP.NET validators on the page and when the page fails to validate, client-side, all of the textboxes that contained hint text are now blank. This is confusing for the end-user because their are no field labels. To see the hint text, they must click in and out of the field and it re-populates.
Not sure if it makes a difference, but these fields are wrapped in an ASP.NET AJAX UpdatePanel. The reason for the update panel is to do some asynchronous calls for dynamic field updates like auto-populating the state dropdown based on what country you choose. The form is submitted via postback.
I need a way to call the hint javascript against these fields after the validation fails on the client side. How can I do this?
Here is an example of the client side code that executes the hint plugin against the various fields on the page:
<script type="text/javascript">
$(document).ready(function () {
// Add handler function to UpdatePanel's events
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
PageLoad();
});
function PageLoad() {
RetainState();
}
// This function handles the UpdatePanels' EndRequest event.
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
RetainState();
}
else { // there was an error
alert("There was an error" + args.get_error().message);
}
}
function RetainState() {
// Add hint to textboxes.
$(":text").hint();
$("textarea").hint();
}
</script>
One last thing: I thought I had already fixed this problem by adding the following code to the Page_Load method in the code behind, but if it was working before, it is not now:
// This will call some javascript after a form validation fails
// and keep the hint text in the form fields.
if (!Page.ClientScript.IsOnSubmitStatementRegistered("KeepState"))
{
string script = "RetainState()";
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "KeepState", script);
}
Thanks,
Tod

Related

Server side alert disturbs page styling

I needed to show a message on web page. I'm using ASP.Net and C#. I added below code in the back-end code to show message to the user
protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
//other code removed for clarity on where and how this alert is triggered
if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
{
Response.Write("<script>alert('Invalid renewal date');</script>");
}
}
This works fine as expected on the event call. But, the moment I click OK button on the alert message, the font-size of the text increases. It looks like somehow this alert message is disturbing my styles on the page.
Does anyone know a safe method to display alert from ASP.Net code behind page?
It is hard to tell what is causing the font shift based on what you posted, but your design can be vastly improved by 1. not making a server call just to validate a date, and 2. not using alert() which locks the whole browser until someone clicks "ok".
You could change your approach to set a few variables in javascript on page load, and then trigger a function on say change of your input or even on button click. your check function could look something like this
_memberExpiryDate = new Date('#memberDetails.ExpiryDate.Date'); // or whatever the notation is to write out server variable here
function validate() {
if (new Date($('#myDateInput').value()) >= _memberExpiryDate.getTime()))
$('#invalidDateLabel').show();
}
this way you're not making unnecessary postbacks, validation can autocorrect as users adjust dates, and there are no alerts in your face.
you can also use a library such as Toastr to show a more graceful message which disappears after a few seconds. but ideally you want to show something right next to the input field like asp.net date validator even
toastr.error('date is expired');
Also you could just use the asp.net range Validator.
See if
<script>setTimeout(function(){alert('Invalid renewal date');},1000);</script>
fixes your issue
Using ClientRegisterScriptBlock
protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
//other code removed for clarity on where and how this alert is triggered
if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
{
ClientScript.RegisterClientScriptBlock
("".GetType(), "s", "<script>alert('Invalid renewal date');</script>");
}
}
This renders the script in the HEAD section

Keeping an ASP.net Submit button grayed out UNTIL all Javascript validations are passed

I would like to keep a button grayed out (ie. non-clickable) until all javascript (client-side) validations are passed.
First of all, I have set the button's "Enabled" property to false, meaning it is greyed out by default when the page loads. And oppositely, here is some js code (we always like to see some code) that enables the button:
var SubmitButton = document.getElementById('<%=SubmitButton.ClientID %>');
SubmitButton.disabled = false;
I have a series of validations taking place in a javascript/jquery block on my page:
<script type="text/javascript">
//Client-Side validation script:
$(function () {
$("#<%=OtherBox.ClientID %>").blur(function () {
//Validation logic goes here...
});
//etc... there are many more.
});
</scipt>
I guess this is more of a javascript question than anything. How do I structure my javascript code to accomplish what I want to do here? In other words, how, when, and where should I set the disabled property of the button to false in my javascript?
One thought was to have a function at the end of my script, which contains all of the logic from each of my validations, and sets the button to be non-greyed out only if all of the logic passes. But using this method, there is no code reuse -- I would simply be copy pasting in all of the logic from each validation function into one mega function. Plus, it would only execute once, which is not good. The button should be able to be re-grayed-out if they change their input data to be invalid.
After thinking about this for a little while longer than I'd like to admit (such a simple problem :[) why don't I just create a loop at the end of my Javascript that is:
while(SubmitButton.disabled = true)
{
//Perform all validation logic from each validation function -- yes it is painful to reuse all of them again, but it is very straightforward.
//If all checks pass, then break out of the while loop by setting SubmitButton.disabled = false.
}

add_endRequest(EndRequestHandler) causing my javascript to popup twice

I have this function in my .aspx file in the beginning
<script type="text/javascript">
function onPageLoad() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
</script>
Now in my javascript I have a function called validate that validates some conditional fields on the form.
function validate() {
// calls alert
alert("Field is blank");
}
Now I also have this function called EndRequesthandler which simply calls my validate.
function EndRequestHandler() {
validate();
}
Now for some reason, if I leave a field blank then popup pops tiwce when I click a SUBMIT button which is under a update panel and does asynchrous postback. I cannot have this field under Required because its required based on another drop downlist. so its conditional. Any help is appreciated.
This seems like an odd implementation of essentially trying to run a client side validation script before the form is submitted if I'm not mistaken?
I suggest you try implementing James McCormack's answer found here: How to capture submit event using jQuery in an ASP.NET application?

jquery tools validation re-bind after loading different content

I'm using the jquery tools validation plugin for client side form validation.
i have one javascript file which loads the function below on ready.
What i'm doing is, i load a form, when this is being validated successfully and submitted,
i load another form, and would like the function below to handle any form thats being loaded
within the if (json.success && json.next) statement block.
For some reason, when the second form is loaded, the validator is not being re-bound to the
class (.signup_form) of the new form, and the validation does not occur.
any idea how i could attach a $.live or anything to this, so it'll automatically rebind itself to whatever form gets loaded with the .signup_form class after success?
/* For clarification: json.next is the url of the next form to load */
$(".signup_form").validator({
position: 'top left',
offset: [-12, 0],
message: '<div><em/></div>' // em element is the arrow
}).submit(function(e) {
var form = $(this);
// client-side validation OK.
if(!e.isDefaultPrevented()) {
// submit with AJAX
$.post(form.attr('action'), form.serialize(), function(json) {
// everything is ok. (server returned true)
if (json.success && json.next) {
form.parent().parent().load(json.next); // Slide here
form.reset();
// server-side validation failed. use invalidate() to show errors
} else {
form.data("validator").invalidate(json);
}
}, "json");
// prevent default form submission logic
e.preventDefault();
}
});
any help is greatly appreciated.
T
Okay, i figured it out... geez its so obvious.
so all of the code above i have within a
form_listener = function() {}
block.
now all i need do do is to call the form listener after i load the new form:
.
.
// everything is ok. (server returned true)
if (json.success && json.next) {
form.parent().parent().load(json.next, function(){
form_listener();
});
.
.
sweet.

change text of asp.net button with javascript

I have a form submit button that has asp.net validators hooked up to it. If I make a javascript function to change the text to processing on click it does not work. The button flags the validators and also causes the whole page to post back. Heres the code I have:
C#
protected void Page_Load(object sender, EventArgs e)
{
btnPurchase.Attributes["onClick"] = "submit()";
}
Html
<script type="text/javascript">
function submit() {
document.getElementById("ctl00_ContentPlaceHolder1_btnPurchase").value = "Processing";
};
</script>
My goal is to change the buttons text to purchasing onclick if the form passes validation, and then in my code behind it will change back to the original value once the form posts back.
I ran across this solution which works 100% perfect. I'm using the script manager with update panels...
<script type="text/javascript">
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Using that prm reference, hook _initializeRequest
// and _endRequest, to run our code at the begin and end
// of any async postbacks that occur.
prm.add_initializeRequest(InitializeRequest);
// Executed anytime an async postback occurs.
function InitializeRequest(sender, args) {
// Get a reference to the element that raised the postback,
// and disables it.
$get(args._postBackElement.id).disabled = true;
$get(args._postBackElement.id).value = "Processing...";
}
// Executed when the async postback completes.
function EndRequest(sender, args) {
// Get a reference to the element that raised the postback
// which is completing, and enable it.
$get(args._postBackElement.id).disabled = false;
$get(args._postBackElement.id).value = "Purchase";
}
</script>
I just asked a very similar question (which was answered):
ASP.NET Custom Button Control - How to Override OnClientClick But Preserve Existing Behaviour?
Essentially you need to preserve the existing behaviour of the submit button (__doPostBack). You do this with Page.GetPostBackEventReference(myButton).
However with validation it's more difficult, so you'll need to do page validation inline (Page.Validate()) or create a custom control like i did and override the OnClientClick and PostBackOptions members.
Custom control is better, as i can now just drop this control on any page i want this behaviour.
You could do the same and expose a public property:
public string loadingText {get; set;}
Which could be used to customise the loading text on each page.
You basically need to set the onclick attribute to do the following:
onclick = "if (Page_Validate()) this.text = 'Processing';{0} else return false;"
{0} should be the regular postback action, retrieved from Page.GetPostBackEventReference.
The resulting logic will be: on click, validate the page, it it succeeds, change the text and postback, if it fails, return false - which will show the validation on the page.
Have the button set to default text "Submit" in the HTML, then wrap the above logic in !Page.IsPostBack so it will reset the text on form submit.
Hope that helps.

Categories