March 23, 2012

Problems with my javascript, I dont want to validate <select> tags that are disabled

Question by ps__

This javascript will find all my selects and validate them but I want to add that it doesnt validate my disabled selects. How can I code that in my javascript?

$("#next-step").click(function () {

                var $step = $(".wizard-step:visible"); // get current step

                var validator = $("form").validate(); // obtain validator
                var anyError = false;
                $step.find("select").each(function () {
                    if (!validator.element(this)) { // validate every input element inside this step
                        anyError = true;
                    }


                });

                if (anyError)
                    return false; // exit if any error found

Thanks in advance!

Answer by ehynds

if (!this.disabled && !validator.element(this)) {
    anyError = true;
}​

or (slower)

$step.find("select:enabled").each(function() {
    if (!validator.element(this)) {
        anyError = true;
    }
});​

Answer by Starx

The easiest way, i know of is to give the select tags, a class like skipvalidation and then

$("form").validate(
   ignore: ".skipvalidation"
);

You can find all the disabled elements and add the class as

$("input:disabled").addClass("skipValidation");
$("form").validate(
   ignore: ".skipvalidation"
);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!