jquery validation not working on hidden fields - javascript

Working on jQuery validator initially some of the field where display none so when the user click next button the error message was showing You have missed 1 fields. Please fill before submitted this was working perfect as i expected. Because I gave ignore:".chk_Field",. But when the user click yes radio button user can able to see some more fields. without filling any of the field If user click the next button still it should say You have missed 5 fields. Please fill before submitted but currently it was saying You have missed 1 fields. Please fill before submitted this is not happening with this line of code ignore:".chk_Field",
Here is my jquery code
function apply_validation() {
$(".educationForm").validate({
ignore:".chk_Field",
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = 'You have missed ' + errors + ' fields. Please fill before submitted.';
$errorMessageDiv.html(message);
$errorMessageDiv.show();
} else {
$errorMessageDiv.hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if ($(element).is(':radio')) {
} else {
$(element).addClass('errRed');
$(".chk_field_hlt").addClass('errRed_chkb');
$('#imageUploadForm').addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if ($(element).is(':radio')) {} else {
$(element).removeClass('errRed');
$(".chk_field_hlt").removeClass('errRed_chkb');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
}
});
}
Here is the fiddle link
Thanks in advance

Try to put this line of code:
$("#expy").find(".chk_Field").removeClass("chk_Field");
Here:
$(".wrk_clp").click(function () {
if ($('input[name=rad_emp]:checked').val() == "yes") {
$expDiv.show();
$("#expy").find(".chk_Field").removeClass("chk_Field");
}
I just tested and it seems to work.

Related

jQuery - Validation

I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.

How to display a confirm box before submitting a form using jquery confirm?

I have a form and I want to show a confirmation massage after clicking submit button and also I don't want to use following method
return confirm("Are You Sure?")
I used JQuery Confirm as following.
#using (#Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
{
.....
<button onclick="SubmitMyForm()">Submit</button>
}
The javascript codes are ...
function ValidateMyform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if (inputs[i].hasAttribute("required")) {
if (inputs[i].value == "") {
// found an empty field that is required
alert("Fill all fields");
return false;
}
}
}
return true;
}
The Javascript code for showing Confirm Box (According JQuery Confirm) is
function SubmitMyForm() {
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return true;
},
Yes: function () {
$("#ReceptionForm").submit();
//alert("For Test");
//document.getElementById("ReceptionForm").submit();
}
}
});
}
The Problem IS...
When I click Submit button it doesn't wait for me to click Yes button in Confirm box and the form will submit (the Confirm box appears and after 1 sec disappear and form submits).
But when I use alert("For Test"); instead of $("#ReceptionForm").submit(); , it works correctly. Does anybody knows why I'm facing this problem?!!!
You could use a "flag" to know if the confirmation occured or not to "prevent default" submit behavior.
Remove the inline onsubmit = "ValidateMyform(this);" and use a jQuery event handler instead.
var confirmed = false;
$("#ReceptionForm").on("submit", function(e){
// if confirm == true here
// And if the form is valid...
// the event won't be prevented and the confirm won't show.
if(!confirmed && ValidateMyform($(this)[0]) ){
e.preventDefault();
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return;
},
Yes: function () {
confirmed = true;
$("#ReceptionForm").submit();
}
}
});
}
});

How to have a custom message validity in Google recaptcha using JS?

How to have a custom message validity in Google recaptcha?
If the user didn't or forgot to checked the Google Recaptcha checkbox before clicked the submit button. There's a popup message will displayed, the the user need to check first the checkbox.
I have JS that will validate the input text box and it is working. But I don't know how to implement it in Google Recaptcha
JS:
function InvalidMsg(textbox){
if(textbox.validity.patternMismatch){
textbox.setCustomValidity('Please enter your name here');
} else if(textbox.validity.valueMissing){
textbox.setCustomValidity('This field is required');
} else {
textbox.setCustomValidity('');
}
return true;
}
You have to use the reCaptcha verify response call back. Something like this: https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit'>
You will also want to attach your error message to the reCaptcha container you are using.
var RC2KEY = 'sitekey',
doSubmit = false;
function reCaptchaVerify(response) {
if (response === document.querySelector('.g-recaptcha-response').value) {
doSubmit = true;
}
}
function reCaptchaExpired () {
/* do something when it expires */
}
function reCaptchaCallback () {
grecaptcha.render('id', {
'sitekey': RC2KEY,
'callback': reCaptchaVerify,
'expired-callback': reCaptchaExpired
});
}
document.forms['form-name'].addEventListener('submit',function(e){
if (doSubmit) {
/* submit form or do something else */
}
else {
/**
* Show your error message here.
* InvalidMsg function may not work.
* recaptcha does not have properties you are checking for.
*/
}
})

Customizing a password strength validator plugin

I am using a plugin called pStrength.jquery.js and for some reason its not submitting the form I have, or it is submitting the form even if it is not supposed to (when I changed the code)
The code i am using is:
$(document).ready(function () {
$('#myForm').submit(function () {
return false;
});
$('#myElement1, #myElement2').pStrength({
'changeBackground': false,
'onPasswordStrengthChanged': function (passwordStrength, strengthPercentage) {
if ($(this).val()) {
$.fn.pStrength('changeBackground', this, passwordStrength);
} else {
$.fn.pStrength('resetStyle', this);
}
$('#' + $(this).data('display')).html('Your password strength is ' + strengthPercentage + '%');
},
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
$('#myForm').submit(function () {
return true;
});
}
});
});
Someone has told me that I should use booleans and inside the validation checks, set it to true or false.
The problem is that i have no idea how to do this
Is there anyone that could help me and show me the code to do this?
Thank you in advance
The reason it was still submitting was because the onValidatePassword function runs on each individual field, whereas you actually had two fields to validate. If one field validates and the other doesn't, the form would still submit because the Boolean had already been set to true, which was the only condition needed to submit.
Updated code below, you can also refer to the fiddle.
$(document).ready(function () {
$('#myForm').submit(function (event) {
// TODO: check that the two field values match as well
if ($('#myElement1').data('valid') === 'yup' &&
$('#myElement2').data('valid') === 'yup') {
// remove these three lines to make it submit
alert('Submitting...');
event.preventDefault();
return false;
// and uncomment this one line
//return true;
} else {
event.preventDefault();
return false;
}
});
$('#myElement1, #myElement2').data('valid', 'nope');
...
Your complete onValidatePassword callback should now look like this:
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
formValid = strengthPercentage >= 60;
// set for each element
if (strengthPercentage >= 60) {
$(this).data('valid', 'yup');
} else {
$(this).data('valid', 'nope');
}
}
Inside your onValidatePassword, you're binding to the submit event, instead of submitting the form. Replace this code:
$('#myForm').submit(function () {
return true;
});
with
$('#myForm').submit();

Having trouble with Javascript autocomplete library when getting data with getJSON

I'm running into issues with the following code:
var setupSearch = {
searchSuggest: function(field) {
$.getJSON('/get-all-journals', {'url':'on'}, function(data) {
var SHCount = Number($.cookie('SHCount'));
var SHArray = new Array();
for (i=1; i <= SHCount; i++) {
SHArray.push($.cookie('SH'+i));
}
$(field).ddautocomplete(removeDuplicate(SHArray), data.response.docs, {
matchContains: true,
max: 5,
cacheLength: 5000,
selectFirst: false,
scroll: false,
formatResult: function(str) { return str; },
formatItem2: function(item) {
return item.journal_display_name;
},
formatMatch2: function(item) {
return item.journal_display_name;
},
formatResult2: function(item) {
return item.journal_display_name;
}
});
});
},
searchForm: function(form) {
var field = form.find('textarea');
// Setup query field for default text behavior
// setupField(field);
setupSearch.searchSuggest(field);
field.autogrow();
field.keydown(function(e) {
if (e.keyCode == 13) {
form.submit();
return false;
}
});
// Make all forms submitting through Advanced Search Form
form.submit(function(e) {
e.preventDefault();
setupSearch.submitSearch(form, field);
});
},
submitSearch: function(form, field) {
if (advancedSearch.checkMinFields() || (!field.hasClass('defaultText') && field.val() != '')) {
// Sync the refine lists
// syncCheckboxLists($('#refineList input'), $('#advancedRefineList input'));
form.find('button').addClass('active');
$('#advancedSearchForm').submit();
} else {
$('#queryField').focus();
}
},
When I try to use the autocomplete drop-down by hitting enter, it seems to hit a "race condition" where the form will submit what I've typed rather than what autocomplete places into the textfield. Is there some way I can control the order of events so that the form.submit() will use what autocomplete fills into the text field?
The actual autocomplete dropdown menu is most likely represented as a styled list (or some other element) that is floated to be positioned below the textbox. On submit, have your function wait (a second or two max) for the autocomplete menu to be either destroyed or hidden. This will ensure that the plugin has time to fill in the textbox before the data is submitted.
EDIT
Try something like this:
$("#myDropdown").bind("autocompleteclose", function(){
// Continue with submitting your form
});
Use that where you would submit your form, and put the submitting code inside the callback. That way, it will wait for the autocomplete to close before submitting the form. You will want to add some kind of timeout to this to prevent it from submitting after a long delay (not sure when something like this might happen, though).

Categories