How to reset qTip2 validation? - validation

I have a form in an ASP.Net MVC project on which I am using qTip2 to display validation erros. On that form, I also have text fields that are activated/deacivated depending on choices made with radio buttons. When fields are not to be used, I set their disabled="disabled" properties. This ensures that client side validation (jQuery unobtrusive validation) for these fields is also deactivated. Now, I am wondering how to reset the qTip2 "bubbles" for fields that get disabled.
Let's say I have radio buttons 1 and 2 that enable text boxes A and B respectively. Let's also say that radio button 1 is selected by default, and that text boxes A and B are required fields when the corresponding radio button is selected. If I press on the Submit button without filling any text field, a qTip error bubble appears beside text box A. Now, if I press on radio button 2, I have to clear that bubble, disable text box A and its validation, and enable text box B and its validation. However, if I press submit at this point without filling text box B, no error bubble appears and the form is not getting submitted.
I tried various combinations of the following commands to accomplish this, but then the validation errors get completely disabled:
$('.qtip').remove();
$('.qtip').hide();
$("input.input-validation-error").removeClass("input-validation-error"); // watch out for the error message labels or they won't go away
$('form').data('validator').resetForm();
$("form").validate().form();
No matter what combinations of these commands I execute after a radio button got clicked and the proper text-boxes disabled/enabled, the qTip bubbles disappear, but they never reappear even if I click on the Submit button and other errors should appear on the form.
I am probably not using the right commands to reset qTip validation bubbles.

Ok, I found a solution right after posting the question. I used the solution proposed on this page http://johnculviner.com/?tag=/unobtrusive-validation-reset that I modified a bit. I added the following line: $form.find('input').qtip('destroy');
It gives this:
//Taken from: http://johnculviner.com/?tag=/unobtrusive-validation-reset
(function ($) {
$.fn.resetValidation = function () {
var $form = this.closest('form');
//Destroy qTip error bubbles (http://craigsworks.com/projects/forums/thread-using-qtip-with-jquery-validation-framework)
//$form.find('input:not(.errormessage)').qtip('destroy');
$form.find('input').qtip('destroy');
//reset jQuery Validate's internals
$form.validate().resetForm();
//reset unobtrusive validation summary, if it exists
$form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul").empty();
//reset unobtrusive field level, if it exists
$form.find("[data-valmsg-replace]")
.removeClass("field-validation-error")
.addClass("field-validation-valid")
.empty();
return $form;
};
//reset a form given a jQuery selected form or a child
//by default validation is also reset
$.fn.formReset = function (resetValidation) {
var $form = this.closest('form');
$form[0].reset();
if (resetValidation == undefined || resetValidation) {
$form.resetValidation();
}
return $form;
}
})(jQuery);
Then when a radio button is clicked, I call $("form").resetValidation(); after the proper fields have been enabled/disabled.

Related

Microsoft Edge "Leave Site" Message Displays when Choosing from Dropdown

I have an inherited MVC5 web application using Razor that when the page loads, there are two drop downs displayed, some data, and five buttons, one of which is disabled (Save). When I select a different option from the first drop down, what is supposed to happen an input field with a date picker is to display, along with an "OK" button, and the "Save" button is supposed to be enabled. This works fine in IE 11, but in Microsoft Edge, a message appears asking "Leave site? Changes you made may not be saved." If I click the "Leave" button, the spinner appears and I stay on the page.
In IE 11, when any other option is selected from the first dropdown, the spinner appears, the page reloads with the input field with date picker, but OK button appears, and the Save button is enabled. The only time a similar message displays is when the back button is clicked.
I went through the code and found the following:
The code for the first drop down:
#Html.DropDownListFor(m => m.StatusId, new SelectList(Model.StatusList, "Value", "Text", Model.StatusId), new { #class = "form-control", #id = "StatusList"})
I also found a submit button that has been hidden:
#Html.HiddenFor(m => m.CurrentTypeName, htmlAttributes: new { id = "CurrentTypeName" })
<input id="FinalizeValidationButton" type="submit" name="action:FinalizeValidation" style="visibility:hidden" />
In a javascript file I found the following:
//This is the first dropdown mentioned above
$('#StatusList').change(
function () {
triggerFinalizeValidation();
setVisibility();
});
var triggerFinalizeValidation = function () {
var selectedStatus = $('#StatusList').val();
$("#CurrentSignificantActivityTypeName").val($("div.active").prop("id"));
if (selectedStatus != 1) {
navParams.userAction = true;
$('#finalizeButton').prop('disabled', true);
navParams.isDirty = false;
$('#FinalizeValidationButton').trigger('click');
}};
So what's happening is, the user selects a different option from the first dropdown (StatusList), which triggers $('#StatusList').change, which in turn calls triggerFinalizeValidation(), which in turn adds a click event to the hidden submit button ("FinalizeValidationButton"). For whatever reason, it's like it triggers a postback like response, which causes Microsoft Edge to think the user is trying to leave the current page, when they are not.
The hidden button, when clicked, executes the following code in the RiskController.ca. There are a number of dropdowns, fields, etc on the screen other than the fields/buttons that have already been mentioned. So the this part of the code validates what the user has selected and peforms calculations based on what was selected. When I comment out the click event in the JavaScript, the browser message doesn't display, but then the FinalizeValidation method doesn't execute either.
[AcceptVerbs(HttpVerbs.Post)]
[MultiButtonAction(Name = "action", Argument = "FinalizeValidation")]
public ActionResult FinalizeValidation(RiskViewModel viewModel)
{
string currentActivityTypeName = viewModel.CurrentActivityTypeName;
var risk = _riskRepository.FindFull(viewModel.Id);
I'm wondering if there is a way to use #onchange in the dropdown to somehow call the FinalizeValidation method in the controller to see if that resolves the browser message from appearing...Thoughts?
I ended up using
$(window).off('beforeunload');
After
$('#FinalizeValidationButton').trigger('click');
Which resolved the issue.

Delaying Kendo Validation until Submitting the form

I have marked my controls with the Required attribute.
This has caused them to not only error on the lost focus event ( which is good ) but the problem is it won't even let me continue entering values in OTHER columns and controls of the grid on the form until I first type something for the required control.
Is there a way to delay this required validation to when I submit the form?
You can bind the .getKendoValidator(); method to your form which allow you to delay your validation.
You need to set button type ="Submit"
Refer the following line of code :-
var form_validator = $("#form_reg").kendoValidator({
rules: {
/*..*/
},
messages: {
/*..*/
}
}).getKendoValidator();
Also note that as the Validator is attached to a form element,
the validation will be executed automatically when the form is submitted, which in this case is when the button is clicked. Therefore, there is no need to manually call the validate method.
Note:-execute some custom logic, like alert to the user, when form is validated you may use
validate event.

How to reset the dropdown value to the old value in jqgrid

I have a simple dropdown with two values.Lets say Staus:active and inactive.
During the onchange event, I want to perfrom some validation and revert back if the validation fails. Thai is if I change from active-inactive and my validation fails, I should change the dropdown back to active.
So far I am able to catch the on change event through the dataevents options of editOptions.
Below is my code, Thanks for the assist.
editoptions:{value:{Y:'Active',N:'Inactive'}, dataEvents:[
{
type: 'change',
fn: function(e) {
alert("inside change trigger");
$grid.setColProp('Status', { editoptions:{value:{Y:'Active',N:'Inactive'}}});
}
}
]}
I also read I have to set recreate form :true. I tried that also.
I would recommend you to consider to make the column non-editable or to readonly/disabled if the validation condition could be checked before editing will be started. It shows the user more clear that the field mayn't be changed.
Alternatively you can get savedRow parameter of jqGrid if you use inline editing mode or cell editing mode (with var savedRows = $(this).jqGrid("getGridParam", "savedRow")). To get the "old" data in case of form editing you can just get the data of selected row by using getGridParam with selrow (or alternatively from the hidden field of the form which have id="id_g". Something like var serRowId = $("#id_g").val();) and by using getRowData/getCell.

How to bypass/dismiss webform validation in drupal 7?

Here is my situation:
I have a very long multi-page survey built by webforms in drupal.
The questions are not required but we don't want the users to skip all the questions too easy by just clicking Next Page button.
So this is what we need:
When the user try to click on "Next Page" button with any empty fields on the page, error or warning messages will show up, "Are you sure you want to skip this question?", as well as a skip button next to it. When the user click on the skip button, the message disappears and they click on the next page button to proceed the survey.
Here are my thoughts on this:
I used webform validation module to create an Not Empty validation and apply it to the fields.
in webform_validation_validators.inc:
case 'skip_if_empty':
foreach ($items as $key => $val) {
if (count($val) == 0) {
drupal_set_message(t('This field is empty.'), 'warning');
// do something, not sure about it here
}
}
Another thought:
I used the Dismiss module to display an X button next to the error message.
Can I add some functions to the X button to bypass the validation when it is clicked?
And here is the script for the Dismiss module, :
(function ($) {
Drupal.behaviors.dismiss = {
attach: function (context) {
$('.messages').each(function () {
var flag = $(this).children().hasClass('dismiss');
if (!flag) {
$(this).prepend('' + Drupal.t('Close this message.') + '');
}
});
$('.dismiss').click(function () {
$(this).parent().hide('fast');
// some functions to bypass validation to the field?
});
}
}
})(jQuery);
I don't know what to do to after the //. Or is there any other ideas that will work?
AS per the you requirement mention
Take this example
You have created webform having field like
Firstname with required field
Lastname with required field
Then Next button button
When user click next button then error show because you have make the fields are required
When your showing "Dismiss button" next to each field.
Whenr user click "Dismiss button" that time you have to remove "required" attribute of field using jquery or drupal ajax
After that when user click next button then user not get any kind of required field validation error.

JQuery Validate and Checkbox Click Function

I have a basic checkbox click function that only allows the user to click only one checkbox within each fieldset (there are four fieldsets each containing numberous checkboxes:
$(document).ready(function(){
$('input[type=checkbox]').click(function(){
// get the fieldset class
var fieldset = $(this).parents('fieldset').attr('class');
// set the number of checked
var numChecked = $('.'+fieldset+' input:checked').size();
// if more than 1
if(numChecked > 1){
alert('Please select only one option per breakout session.')
$(this).attr('checked',false);
}
});
Then I have a submit function on the form that will confirm that at least one checkbox is selected before posting the form:
$('form[name=mainForm]').submit(function(){
var error = '';
// loop through each fieldset
$('fieldset',this).each(function(){
// set the number of checked for this fieldset
var numChecked = $('input:checked',this).size();
// if none are checked
if(!numChecked){
// set the error var
error = 'At least one of your time sessions has no checkbox selected!';
// add class to show user
$(this).addClass('errorSessions');
}
else{
$(this).removeClass('errorSessions');
}
});
// if any errors, show them and don't allow the form to be submitted
if(error.length){
alert(error);
return false;
}
$("#mainForm").validate();
The form validates perfectly and everything happens flawlessly the first time around. The problem is that if you submit the form, the validation occurs and it gives the error "At least one of your time sessions has no checkbox selected!" - at that point if you proceed to select multiple checkboxes within a given fieldset that was not initially checked, it will ignore the checkbox click function and allow you to select more than one checkbox in a fieldset.
Can someone please help with this?
Okay, I figured it out. The error has to do with the script adding the class 'errorsessions' to the fieldset which changes the unique classname of the fieldset. By adding a unique id to each fieldset and then changing the script to reference .attr('id'); instead of .attr('class'); the issue resolved and the on click alert function resumed after the class was added.
Do you consider using radio buttons as they are there for single selection? This way you don't have to check for multi selection as it isn't possible for select more than one radio button in given group.

Resources