I am trying to use the Jquery Validate Plugin and I was able to figure out how to use it on static fields.
My problem is on how to used it on my dynamic forms. I created a fiddle to discuss my problem. Hope you can have patience on reading this. The fiddle link is here
Now, here's what I want to do, validate the Machine ID entered on each text box and make sure that it is unique. Say you enter ABCD-123 twice, the system should alert you that it is not unique.
Hoping somebody could lend me a hand on this. Thanks
first of all - put comments in your code while you write.
the error is here:
var arrElements = $(".machineID");
arrElements is always empty, there is no element with machineID class
and your each doesn't work. I refactored it http://jsfiddle.net/PaTJ4/
Your code could use some more fixes, it's a bit too complicated for that task. But now it works.
good luck
I've improved on your version - when a duplication is detected, any one of the duplicated fields should be marked as invalid, and should be able to be changed in order to fix the problem. So, you'd need to revalidate all other fields every time (using validator.element()), but avoid a recursion (using validator.validatingOthers).
I'll post the code for checkMachineIDs here for completeness:
function checkMachineIDs(element){
if($(element).val() != ""){
var arrElements = $("#machineList .machineID");
var $element = $(element);
var validator = $($element[0].form).validate();
if(arrElements.length > 1){
var valid = true;
arrElements.not('#'+$element.attr('id')).each(function() {
var current = $(this);
if (current.val() == $element.val())
valid = false;
});
if (!validator.validatingOthers) {
validator.validatingOthers = true;
arrElements.not('#'+$element.attr('id')).each(function() {
validator.element(this);
});
if (valid) validator.element($element);
validator.validatingOthers = false;
}
return valid;
}else{
return true;
}
}else{
return true;
}
}
Related
First and foremost: I’m using Webflow, so the issue can be related to Webflow somehow.
Second, I’m still learning to code, so please keep in mind that I’m still a newbie.
I’m using two same forms (different classes since, well, they are two separate elements) on a site because the one is static and another one is located in CMS (Collection List).
The thing is, they did work together before, but I did something, and… well, you know — I’ve tried to debunk what happened, but didn’t find a proper solution.
For some, very-very strange reason, only the latter works, e.g., if jobs-form-cms-button is the first, then it won’t work, but jobs-form-button will. And vice versa.
function checkform() {
const formElements = document.forms["wf-form-jobs"].elements;
let submitBtnActive = true;
for (let inputEl = 0; inputEl < formElements.length; inputEl++) {
if (formElements[inputEl].value.length == 0) submitBtnActive = false;
}
if (submitBtnActive) {
document.getElementById("jobs-form-button").disabled = false;
} else {
document.getElementById("jobs-form-button").disabled = "disabled";
}
};
function checkform() {
const formElementsCMS = document.forms["wf-form-cms-jobs"].elements;
let submitBtnActiveCMS = true;
for (let inputEl = 0; inputEl < formElementsCMS.length; inputEl++) {
if (formElementsCMS[inputEl].value.length == 0) submitBtnActiveCMS = false;
}
if (submitBtnActiveCMS) {
document.getElementById("jobs-form-cms-button").disabled = false;
} else {
document.getElementById("jobs-form-cms-button").disabled = "disabled";
}
};
I’ve renamed some vars and const because it didn’t work otherwise. Also, I did some stuff in order to make this code work with Webflow since I couldn’t add some attributes to the native Webflow elements, e.g., “Form Button” (“disabled” attribute was reserved for the system) — so I added the forms by myself via custom code element.
Both functions have the exact same name, in JavaScript when both functions have the same name, the 2nd function will override the first function.
I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime
I'm using jsPsych in behavioral research. The developer of that library is very helpful, yet also busy, so I wanted to try and see if the stack overflow community could help me out with a more general js problem :)
In the instance where I'm getting issues, I push objects into an empty array to update the site after input. In this particular case, I use a script that allows me to use external html pages. My problem is, that, while this function here works in order to correctly display a java prompt when assessing a checkbox
var check_consent = function(elem) {
if ($('#consent_checkbox').is(':checked')) {
return true;
}
else {
alert("If you wish to participate, you must check the box next to the statement 'I agree to participate in this study.'");
return false;
}
return false;
};
this here doesn't work in order to assess a text box
var inp = $("#ctry_box").val();
var check_sociodemo = function(elem) {
if ($.trim(inp).length > 0) {
return true;
}
else {
alert("Please fill out the form.");
return false;
}
return false;
};
More specifically, the prompt does actually work, but no matter what you type into "ctry_box", you can't continue the page and the prompt is shown no matter what the input.
Further, the developer set "data" as a object property designed to store data in accordance with individual variable choices. Regarding the same html files, I would like to gather the input from another text box like this
var sociodemo_block = {
type: 'html',
pages: [{url: "text/sociodemo.html", cont_btn: "end", check_fn: check_sociodemo}],
data: [{age: age_box.value}],
force_refresh: true
If I run this, the console tells me that age_box is not defined. Yet again, #consent_checkbox did work. Am I missing something fundamentally here or are the variables simply not shared across the files properly?
I'm very thankful for any help!
I'm using Parsley.js to validate part of a form like in this example. However, the validate() method always returns false, even when that piece of form should validate.
No error messages are displaying, and I want to see what it is that's failed validation.
I can't see a way to get Parsley to simply return all the errors found, so I can see them in the console. Have I missed something obvious?
You can use something like this:
window.Parsley.on('field:error', function() {
// This global callback will be called for any field that fails validation.
console.log('Validation failed for: ', this.$element);
});
from http://parsleyjs.org/doc/index.html#events
There are probably (hopefully) better ways to do this, but this kind of thing is what I ended up using to get some insight into what's being validated and what is/isn't passing:
function validateAnswers(groupName) {
var formInstance = $('.my-form').parsley();
var isValid = formInstance.validate(groupName);
// Just for debugging:
$.each(formInstance.fields, function(idx, field) {
if (typeof field.validationResult === 'boolean') {
// Validated.
console.log('Passed: ' + field.value);
} else if (field.validationResult.length > 0) {
console.log('Failed: ' + field.validationResult[0].assert.name);
}
});
return isValid;
}
This worked on my very simple form with 'required' radio buttons; no idea how it would work on larger forms with different types of fields and validation requirements.
Any better answers or improvements?
Here's what I did for this type of situation.
var formElements = $('form .elementClass').parsley(); // Get all elements inside your form
// Loop through all the elements found
_.forEach(formElements, function(formElement) { //You can use a regular for loop if you prefer
var errors = ParsleyUI.getErrorsMessages(formElement); //Get the list of errors for this element
if (errors.length) {
// Output the first error in the array. You could loop this too.
console.log(errors[0]);
}
});
It feels a bit ugly, but it gets you what you need.
I have code like below to perform some conditional validation on fields in my form. The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required.
jQuery.validator.addMethod('readingRequired', function (val, el) {
//Readings validation - if a reading or a date is entered, then they should all be ntered.
var $module = $(el).closest('tr');
return $module.find('.readingRequired:filled').length == 3;
});
//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
'readingRequired': true
});
//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {
var inputs = parent.find('input');
var required = false;
if (parent.find('input:filled').length > 0) {
required = true;
}
if (required) {
inputs.addClass("readingRequired");
}
else {
inputs.removeClass("readingRequired");
}
}
//This is in the document.ready event:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
This works fine, and I've used pretty much the same code on other pages with success. The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. Does anybody have any idea why this might be happening?
Hmm. You know how it goes, post a question and then find a solution yourself. Not sure why this works exactly, but changing my binding from:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
to
$("input.reading").blur(function () {
SetReadingValidation($(this).closest("tr"));
});
Seems to have solved this issue. Would still appreciate being enlightened as to why that might be...