Compare duplicate values of two select in materializecss framework - javascript

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

Related

Using jquery to remove Parsley Excluded doesn't seem to work

I have a task which required me to selectively validate an input using parsley, then exclude it from parsley once a valid value is entered (make it read only). BUT if the user clears it out, I need to remove the excluded data attribute, and re-bind parsley to the form. I'm doing all of this, but it's as if either a. excluded isn't actually removed, or b. parsley isn't re-bound. Here's some code:
var handleValidation = function($form, type){
//this works for the initial validation. Meaning it will return
//false the first time (before I add/remove the excluded data attr)
var formId = $form.attr('id');
var valid = $('#' + formId).parsley().validate({group: ""+type + "-validation", force: true});
return valid;
};
var reBindParsley = function(parsleyDef,formId){
$('#' + formId).parsley().destroy();
parsleyDef();
};
$clearIcon.click(function(){
//find input traversing the dom
$input.prop("readonly", false); //this works fine
$input.removeData('parsley-excluded'); //not sure if this is needed
$input.removeAttr('data-parsley-excluded'); //this gets removed from the visual representation of the DOM,
//but when i call validation on it, it's as if it's still there
reBindParsley();
})
//this will handle validating the input
$myInput.click(function(){
var valid = handleValidation($form, type);
if(valid){
makeReadOnly() //adds $myInput.attr('data-parsley-excluded', true);
reBindParsley(parsleyFunction, form);
}
});
So after calling the code in the clearIcon click event, the nexst time i click the input, it should call handleValidation(), and return false if the value isn't valid (like it does the FIRST time), but doesn't. I checked the visual representation of the DOM in firefox debugger, and the excluded data isn't there.
Any help is greatly appreciated!
Not 100% what's going on, but there is a simpler way.
$input.removeData('parsley-excluded') is not needed, nor is calling destroy.
var formId = $form.attr('id'); var valid = $('#' + formId).parsley... is simply $form.parsley...
Simply add to the form's excluded list [readonly] and you should be pretty much good to go. Otherwise, please post a working fiddle.

input validation vs. required to submit on multi-page forms

i have a multi-page form that i am trying to validate using jquery validate. the user has essentially 4 options: next, prev, save, submit.
save, next, and prev all save the current page to the form as a whole; submit is the same as save, but fires some additional workflow-related functions then heads off to another part of the site.
i need to validate the user input at all times. the jquery validate is working great. but... i need to have some fields set as required. because the form is saved at each step, the input needs to always be valid, but i don't need the required validation until the very end (on submit).
the form is building a dynamic list of validations specific to the page it is on, like:
$(document).ready(function() {
$("#ctl01").validate({ onsubmit: false });
$("#_Qn_0e868ebe").rules("add", { maxlength: 200 });
$("#_Qn_d69e75a4").rules("add", { number: true });
$("#_Qn_adffbdec").rules("add", { maxlength: 200 });
$("#_Qn_adffbdec").rules("add", { digits: true });
});
so now, for required fields, i've added a .isrequired class to them, and i've decoupled the <asp:linkbutton>s to fire this client script:
function FormIsValid(sender, ishardsubmit) {
var form = $("#ctl01");
form.validate();
if (form.valid()) {
//if (ishardsubmit) {
// if (!IsRequiredValid()) { return false; }
//}
__doPostBack(sender, '');
}
return;
}
this part (the input validation part) is working great so far. the part i commented out is the part that is working not so great. it fires this function, in which i was trying to dynamically add required validators and re-evaluate the form. i can see it hit the .each loop for each of my required fields, but it doesn't seem to be working since it passes true back, even when required fields are empty.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function (i, item) {
$(item).rules("add", { required: true });
});
form.validate();
return form.valid();
}
i toyed with the idea of dropping the .net required field validators in to do this part, but i want to, if possible, stick with a single solution. especially since this feels so close to working.
thoughts? help? thanks!
Your jQuery .each() method is constructed improperly.
You want to target the whole object in your iteration, not key/value pairs. So remove i, item from the function arguments and use $(this) as the target selector.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function() {
$(this).rules("add", { required: true });
});
// form.validate(); // remove this line -> 100% superfluous
return form.valid();
}
Regarding your form.validate() line in both functions: You cannot call .validate() more than once on the page. It's only meant to be called once to initialize the plugin on your form.
Calling it subsequent times will have no effect. Otherwise, we wouldn't need to use the .rules() method as we would simply call .validate() any time we need to change rules. However, this is definitely not the case.
Add a class to your required fields called something like: "SubmitRequired"
Implement two functions as follows:
function SaveClick(){
//ignore SubmitRequired on save (and any disabled fields)
$("form").validate({ ignore: ".SubmitRequired, [disabled]" });
if $("form").valid()
{
do something;
}
}
function SubmitClick(){
//ignore only disabled fields (if any))
$("form").validate({ ignore: "[disabled]" });
if $("form").valid()
{
do something;
}
}

jQuery nested phone number validation

Does anyone know how to use the jQuery validation plug-in while looping through inputs? The only way I know how to make the validation plug-in work is through a submit request. However, I am working on a multi-part form that validates on each step of the form and simply highlights required fields as the user moves through. I would like to add validation to this process as well, just not sure how to do it. Ideally, I'd like to validate more than just phone numbers, maybe email format and reg exp as well. Here the code I'm currently using:
function validateStep(step) {
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == ''){
if($(this).hasClass('req')) {
hasError = true;
$this.addClass('hasError');
}
else
$this.removeClass('hasError');
} else {
$this.removeClass('hasError');
}
});
}
Any ideas?
The code in your question is not making a whole lot of sense to me. If you want to use the jQuery Validation plugin, then validation is handled automatically, you do not need to manually loop through any inputs.
As far as multi-step forms, there are many possible approaches. I prefer to use an individual form element for each step. Then I use the .valid() method to test the section before moving to the next. (Don't forget to first initialize the plugin; call .validate(), on all forms on DOM ready.)
Then on the last section, I use .serialize() on each form and concatenate them into a data query string to be submitted.
Something like this...
$(document).ready(function() {
$('#form1').validate({ // initialize form 1
// rules
});
$('#gotoStep2').on('click', function() { // go to step 2
if ($('#form1').valid()) {
// code to reveal step 2 and hide step 1
}
});
$('#form2').validate({ // initialize form 2
// rules
});
$('#gotoStep3').on('click', function() { // go to step 3
if ($('#form2').valid()) {
// code to reveal step 3 and hide step 2
}
});
$('#form3').validate({ initialize form 3
// rules,
submitHandler: function (form) {
// serialize and join data for all forms
var data = $('#form1').serialize() + '&' + $('#form2').serialize() + '&' + $(form).serialize()
// ajax submit
return false; // block regular form submit action
}
});
// there is no third click handler since the plugin takes care of this
// with the built-in submitHandler callback function on the last form.
});
Important to remember that my click handlers above are not using type="submit" buttons. These are regular buttons, either outside of the form tags or type="button".
Only the button on the very last form is a regular type="submit" button. That is because I am leveraging the plugin's built-in submitHandler callback function on only the very last form.
"Proof of Concept" DEMO: http://jsfiddle.net/j8vUt/
See this for reference: https://stackoverflow.com/a/19546698/594235

jQuery validate - adding a rule causes validation to fire

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...

Displaying Message near TextBox using Javascript

I am having an aspx form and in that i need to do validations using jquery or javascript.
I just want to give a message near to the textbox if a user enter a value which is not valid in that textbox.Inorder to display the message in a popup [not alert('message')]
How can I find the position of the textbox in which user enters the invalid data or how can i display a message near the textbox using javascript or jquery ?
I need the validation occur in blur.So it is easy for user to know whether he entered a valid data immediately after giving the input.
Thanks in advance.I am not interested to use asp.net ajax validation and its callout extender.
I just want to implement a functionality which is similar to validation callout extender does.
When you bind the blur event to the textbox, you know which textbox it is. Just use your callback javascript to insert the error near by.
If you're doing jquery, it might look something like:
$('.my_textboxes').blur(function() {
var textbox = $(this);
//ajax validation call
$.post('/whereever', {}, function(response) {
//ajax callback
if (response == 'error') {
textbox.next().html(error); //something like this to insert the error into the next element after the texrbox, eg, a span to hold the error
}
});`
You can use the jQuery (ASP.NET) Validator Callout Plugin
You can use the jQuery validation plugin
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
Which has options to specify the message beside the control or to specify all the message at one place.
The demos are available at
http://docs.jquery.com/Plugins/validation
Exactly how you do this depends on the layout of your form, but in general you probably would do something like this: if the validation returns an error for a text field, check to see if an "error box" already exists for that field. If so, then just update its contents with the new error message; if not, then add the error element.
One way to do that would be to use a <span> tag with a particular class (for layout purposes), and an "id" value made from the input field's "name" or "id":
$.fn.setValidationResult = function(errorMessage) {
return this.each(function() {
var errId = 'errMsg_' + this.name, errMsg = $('#' + errId);
if (!errMsg.length) {
$(this).after($('<span></span>', { class: 'validation-error', id: errId }));
errMsg = $('#' + errId);
}
if (errorMessage)
errMsg.html(errorMessage).show();
else
errMsg.html('').hide();
});
});
Then you can just use $(yourInput).setValidationResult(whatever); with "whatever" being empty when validation passes.

Categories