Created
July 25, 2012 21:03
-
-
Save reefdog/3178666 to your computer and use it in GitHub Desktop.
Possible form validation autothing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function($){ | |
| $.fn.observeRequirements = function(fnRequirementsMet, fnRequirementsUnmet) { | |
| fnRequirementsMet = fnRequirementsMet || function(){}; // Empty fns may not be necessary | |
| fnRequirementsUnmet = fnRequirementsUnmet || function(){}; | |
| var $wrappers = $(this); // I do this to help distinguish `this` once things get nesty | |
| var requirementsMet = true; | |
| $wrappers.each(function(){ // .each to support operating on element collections | |
| var $wrapper = $(this); | |
| $wrapper.find('*:required:not(:disabled)').each(function(){ // this selector may not work, I dunno | |
| var $element = $(this); | |
| switch ($element.get(0).nodeName.toLowerCase()) { | |
| case 'input': // not sure i'm properly nesting ifs within a case, sorry | |
| if ($element.attr('type').toLowerCase() == 'text' || $element.attr('type').toLowerCase() == 'password' || $element.attr('type').toLowerCase() == 'hidden') { | |
| $element.on('keypress', function(){ | |
| if (!$element.val() != '') | |
| requirementsMet = false; | |
| }); | |
| } | |
| else if ($element.attr('type').toLowerCase() == 'radio' || $element.attr('type').toLowerCase() == 'checkbox') { | |
| $element.on('change', function(){ | |
| if (!$element.prop('checked')) | |
| requirementsMet = false; | |
| }); | |
| } | |
| break; | |
| case 'textarea': | |
| $element.on('keypress', function(){ | |
| if (!$element.val()) // this may not be how you check textareas | |
| requirementsMet = false; | |
| }); | |
| break; | |
| case 'select': | |
| $element.on('change', function(){ | |
| if (!$element.val()) // this may not be how you check selects | |
| requirementsMet = false; | |
| }); | |
| break; | |
| } | |
| }); | |
| }); | |
| if (requirementsMet) | |
| fnRequirementsMet; | |
| else | |
| fnRequirementsUnmet; | |
| return $wrappers; | |
| }; | |
| })(this.jQuery); | |
| $('#my_form').observeRequirements(function(){ | |
| $("#save_new_type").attr('disabled', false); | |
| }, function(){ | |
| $("#save_new_type").attr('disabled', true); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment