I wrote a plugin to validate forms across the network where i work. The problem here is that some of our pages have multiple forms and the global variables get overwritten. I’ll try to give an example as best i can. The code itself would be too long to paste.
I know this code is horribly wrong but i’m trying to gauge the best way to achieve using multiple instances of this code without making things too complicated.
jquery plugin:
(function($){
methods = {
'method1': function(){
alert('form: ' + globals.form_name );
}
}
$.fn.validationplugin = function() {
globals.form_id = $(this).attr('id');
}(jQuery);
var globals = {}
}(jQuery);
html calls:
<form id="form1"></form>
<form id="form2"></form>
<script type="text/javascript">
$('#form1').validationplugin();
$('#form2').validationplugin();
</script>
Use an array for the form identities:
The plugin can be called with a single element or several elements, so you have to get the identities for each element. Also return
thisfrom the function so that the plugin can be chained. Also, you don’t want(jQuery)at the end, as that will call the function and assign the return value as the plugin:Now it also works when there is more than one element in the call:
Consider if you can use the reference to the elements instead of their identity, then it would work for a form without an identity also.