Jquery validation not working after clearing a form - asp.net

I have applied validation through JQuery Validation Plugin on my page. The validation works fine but once the Clear button is hit to clear out all the fields on the form, and then the save button is clicked again, the validation doesn't fire and the form gets submitted. I have called the following javascript function on click of Clear button to clear out all the form fields :-
function ResetForm() {
jQuery(':input', '#form1')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
return false;
}
The Clear button is on a ChildPage and ResetForm function is on the MasterPage. Anybody have any guess why its getting submitted after clearing the fields ?

input is an element and not a attribute or a pseudo selectable, the main issue I see in your code is the : within the :input
Try changing to jQuery('#form1 input') to fetch the list of inputs
Also change the not() command to select filter the inputs by type
.not('[type="button"], [type="submit"], [type="reset"], [type="hidden"]')
also as for :hidden there's several factors you should know about this.
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
In light of your comment please try this tested version:
function resetForm()
{
$("#form1").find(':input').each(function()
{
var jelem = $(this);
switch(this.type)
{
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
jelem.val('');
break;
case 'checkbox':
case 'radio':
jelem.attr('checked',false);
}
});
}
#source: http://www.electrictoolbox.com/jquery-clear-form/
Another way to do this is to create a hidden input in your form but set the type as reset like so:
<input type="reset" style="display:none" />
and then do:
function resetForm()
{
$("#form1[type='reset']").click();
}

Actually the error was something else, the code provided by RobertPitt is correct for clearing of form fields and my code was also correct for clearing of form fields. But the problem is that, on the clear button I had applied a class="cancel" so that the form should not get submitted because it was an aspx:button.
But according to what is written in JQuery docs, clicking of a button whose class is cancel should skip the validation, but after that if I click on a normal submit button validation should fire which was not firing in my case.
I just removed the cancel class and it worked.

Does this help?
Reseting the form when usering the jquery validations plugin

Related

Prevent ASP.NET textbox within a form from submitting the form

Here's the page I'm working on:
http://mcstevenswholesale.com/catalog.aspx
The textbox below the catalog allows you to skip to a specific page in the catalog. However, if you hit enter in that textbox rather than clicking the "Go" button, it submits the search function in the upper left column. I thought this would be because the entire page is located within an ASP form, but I don't have the same problem with the email signup box on the right side.
I have tried putting the page number textbox into its own HTML form, and have tried changing the button to an image, a button, and a submit input. None of these have worked. I don't want the page to reload, just the page to flip. I'm fairly new to ASP, so I'm sorry if I'm making a very obvious mistake.
Here's the code for the page number textbox (goToPage is a JS function that flips the catalog page):
<div id="goToPage">
Go to Page:
<input id="pageTextbox" type="text" onkeydown="if (event.keyCode == 13) goToPage();"></input>
<a onclick="goToPage()" href="#"></a>
</div>
The onkeydown makes the page change work, but it still fires the search function. How do I prevent it from doing that?
The default behavior of the enter key is to submit the current form in most (if not all) browsers.
You need to suppress the enter key's default behavior. The proper way to suppress the default behavior is to have the event handler return false.
If goToPage() returns false the simplest solution is the following:
onkeydown="if (event.keyCode == 13) return goToPage();"
If not you can add return false after the call to goToPage();
onkeydown="if (event.keyCode == 13) { goToPage(); return false} "
That will cause the enter key to not submit the form when pressed within the page number text box. If you want to disable it for the entire page see the following:
http://webcheatsheet.com/javascript/disable_enter_key.php
https://stackoverflow.com/questions/6017350/i-need-javascript-function-to-disable-enter-key
Try this:
onkeydown="if (event.keyCode == 13) { goToPage(); return false; }"

Whats the difference if I set hidden field value through html anchor OR asp.net linkbutton?

The problem is, I have a set of links onclick of those links I am setting the linkId into a Hidden field. First my link were asp:linkbutton ans onClientClick I was setting the hiddenfield value.that time I was able to get the hidden field value from code behind but when I changed my links to HTML anchor and onClick I set the hidden field value , I am not getting hidden field with blank. when I debug JavaScript it is perfectly setting the hidden field value but why I am not getting it in code behind---my code-
<a href="./ContentPage.aspx" data-flexmenu='flexmenu1' onclick="javascript:setPageLinkId(1);">
<script type="text/javascript">
function setPageLinkId(lnkPageId) {
debugger;
alert(lnkPageId);
document.getElementById('<%=hdnSelectedLink.ClientID %>').value = lnkPageId.toString();
}
</script>
//code behind- here I get blank hidden field
if (hdnSelectedLink.Value != null && hdnSelectedLink.Value != "")
{
GetLinkPage(Convert.ToInt32(hdnSelectedLink.Value));
}
Whats the problem ,Please suggest?
My theory is that the click on the anchor doesn't cause a postback to the page. Rather a HTTP GET Request to "ContentPage.aspx" is issued, meaning that any form values are not posted to the server.
You need to use a control that causes a postback to the page...for example ASP:LinkButton as you had before.
#Ozzy you were right dude.I used this in my javascript-
document.forms["aspnetForm"].submit();
its working fine now.

How do I clear MVC client side validation errors when a cancel button is clicked when a user has invalidated a form?

I have a partial view that is rendered within a main view. The partial view takes advantage of System.ComponentModel.DataAnnotations and Html.EnableClientValidation().
A link is clicked, and div containing the partial view is displayed within a JQuery.Dialog().
I then click the save button without entering any text in my validated input field. This causes the client side validation to fire as expected, and display the '*required' message beside the invalid field.
When the cancel button is clicked, I want to reset the client side MVC validation back to it's default state and remove any messages, ready for when the user opens the dialog again. Is there a recommended way of doing this?
This answer is for MVC3. See comments below for help updating it to MVC 4 and 5
If you just want to clear the validation-messages so that they are not shown to the user you can do it with javascript like so:
function resetValidation() {
//Removes validation from input-fields
$('.input-validation-error').addClass('input-validation-valid');
$('.input-validation-error').removeClass('input-validation-error');
//Removes validation message after input-fields
$('.field-validation-error').addClass('field-validation-valid');
$('.field-validation-error').removeClass('field-validation-error');
//Removes validation summary
$('.validation-summary-errors').addClass('validation-summary-valid');
$('.validation-summary-errors').removeClass('validation-summary-errors');
}
If you need the reset to only work in your popup you can do it like this:
function resetValidation() {
//Removes validation from input-fields
$('#POPUPID .input-validation-error').addClass('input-validation-valid');
$('#POPUPID .input-validation-error').removeClass('input-validation-error');
//Removes validation message after input-fields
$('#POPUPID .field-validation-error').addClass('field-validation-valid');
$('#POPUPID .field-validation-error').removeClass('field-validation-error');
//Removes validation summary
$('#POPUPID .validation-summary-errors').addClass('validation-summary-valid');
$('#POPUPID .validation-summary-errors').removeClass('validation-summary-errors');
}
I hope this is the effect you seek.
If you are using unobtrusive validation that comes with MVC you can simply do:
$.fn.clearErrors = function () {
$(this).each(function() {
$(this).find(".field-validation-error").empty();
$(this).trigger('reset.unobtrusiveValidation');
});
};
------------------------------------------------------------------------
Third Party Edit:
This mostly worked in my case, but I had to remove the $(this).find(".field-validation-error").empty(); line. This appeared to affect the re-showing of the validation messages when resubmitting.
I used the following:
$.fn.clearErrors = function () {
$(this).each(function() {
$(this).trigger('reset.unobtrusiveValidation');
});
};
and then called it like this:
$('#MyFormId input').clearErrors();
function resetValidation() {
$('.field-validation-error').html("");
}
You can simply define a new function in jQuery:
$.fn.resetValidation = function () {
$(this).each(function (i, e) {
$(e).trigger('reset.unobtrusiveValidation');
if ($(e).next().is('span')) {
$(e).next().empty();
}
});
};
and then use it for your input fields:
$('#formId input').resetValidation();
Thank you. I had a similar question for a slightly different scenario. I have a screen where when you click one of the submit buttons it downloads a file. In MVC when you return a file for download, it doesn't switch screens, so any error messages which were already there in the validation summary remain there forever. I certainly don't want the error messages to stay there after the form has been submitted again. But I also don't want to clear the field-level validations which are caught on the client-side when the submit button is clicked. Also, some of my views have more than one form on them.
I added the following code (thanks to you) at the bottom of the Site.Master page so it applies to all of my views.
<!-- This script removes just the summary errors when a submit button is pressed
for any form whose id begins with 'form' -->
<script type="text/javascript">
$('[id^=form]').submit(function resetValidation() {
//Removes validation summary
$('.validation-summary-errors').addClass('validation-summary-valid');
$('.validation-summary-errors').removeClass('validation-summary-errors');
});
</script>
Thanks again.
You can tap into the validation library methods to do this.
There are two objects of interest: FormContext and FieldContext. You can access the FormContext via the form's __MVC_FormValidation property, and one FieldContext per validated property via the FormContext's fields property.
So, to clear the validation errors, you can do something like this to a form:
var fieldContexts = form.__MVC_FormValidation.fields;
for(i = 0; i < fieldContexts.length; i++) {
var fieldContext = fieldContexts[i];
// Clears validation message
fieldContext.clearErrors();
}
// Clears validation summary
form.__MVC_FormValidation.clearErrors();
Then, you can hook that piece of code to whichever event you need.
Sources for this (quite undocumented) insight:
http://bradwilson.typepad.com/presentations/advanced-asp-net-mvc-2.pdf (Mentions FieldContext)
https://stackoverflow.com/a/3868490/525499 (For pointing out this link, which metions how to trigger client-side validation via javascript)
In order to complete clear the validation artifacts including the message, the coloured background of the input field, and the coloured outline around the input field, I needed to use the following code, where this was (in my case) a Bootstrap modal dialog containing an imbedded form.
$(this).each(function () {
$(this).find(".field-validation-error").empty();
$(this).find(".input-validation-error").removeClass("input-validation-error");
$(this).find(".state-error").removeClass("state-error");
$(this).find(".state-success").removeClass("state-success");
$(this).trigger('reset.unobtrusiveValidation');
});
Here you can use simply remove error message
$('.field-validation-valid span').html('')
OR
$('.field-validation-valid span').text('')
I've this issue for "Validation summery" after form ajax submit and done it like this:
$form.find('.validation-summary-errors ul').html('');
and complete code is:
$("#SubmitAjax").on('click', function (evt) {
evt.preventDefault();
var $form = $(this).closest('form');
if ($form.valid()) {
//Do ajax call . . .
//Clear validation summery
$form.find('.validation-summary-errors ul').html('');
}
});

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

What is the best approach for (client-side) disabling of a submit button?

Details:
Only disable after user clicks the submit button, but before the posting back to the server
ASP.NET Webforms (.NET 1.1)
Prefer jQuery (if any library at all)
Must be enabled if form reloads (i.e. credit card failed)
This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)
For all submit buttons, via JQuery, it'd be:
$('input[type=submit]').click(function() { this.disabled = true; });
Or it might be more useful to do so on form submission:
$('form').submit(function() {
$('input[type=submit]', this).attr("disabled","disabled");
});
But I think we could give a better answer to your question if we knew a bit more about the context.
If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure.
If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions.
You could do something like this:
$('form').submit(function() {
$(this)
.find(":submit,:image") // get all the submit buttons
.attr({ disabled : 'disabled' }) // disable them
.end() // go back to this form
.submit(function() { // change the onsubmit to always reject.
return false;
})
;
});
Benefits of this:
It will work with all your forms, with all methods of submission:
clicking a submit element
pressing enter, or
calling form.submit() from some other code
It will disable all submit elements:
<input type="submit"/>
<button type="submit"></button>
<input type="image" />
it's really short.
I'm guessing that you don't want them to hit the submit button more than once while the submit is processing.
My approach has been to just hide the button entirely and display some sort of status indicator (animated gif, etc) instead.
Here's a very contrived example (it's technically in prototype but I think a jquery version would be very similar):
<html>
<head>
<script type="text/javascript" src="include/js/prototype.js"></script>
<script type="text/javascript">
function handleSubmit()
{
$('submit').hide();
$('progressWheel').show();
return true;
}
</script>
</head>
<body>
<img src="include/images/progress-wheel_lg.gif" id="progressWheel" style="display:none;"/>
<input type="submit" name="submit" id="submit" value="Submit" onclick="handleSubmit();"/>
</body>
</html>
in JQuery:
$('#SubmitButtonID').click(function() { this.disabled = true; });
On thing to be aware of is that you should not disable the button before the form is submitted. If you disable the button using javascript in the OnClick event you may lose the form submit.
So I would suggest you hide the button using javascript by placing an image above it or by moving the button out of the visible range. That should allow the form submit to proceed normally.
There are three ways to submit a form that should be covered. Use both David McLaughlin's and Jimmy's suggestions. One will disable the submit button form element while the other disables the basic HTML form submit.
For the third, these won't disable Javascript from doing a form.submit(). The OnSubmit="return false" method only applies when a user clicks the submit button or presses Enter in a input form element. Client side scripting will need to be handled as well.
How about
Code behind:
btnContinue3.Attributes.Item("onclick") = "disableSubmit()"
Javascript:
function disableSubmit() {
document.getElementById('btnContinue3').onclick = function() {
alert('Please only click once on the submit button!'); return false;
};
}
This doesnt solve the problem of what happens if the postback times out, but other than that it worked for me.

Resources