I am writing my own form validation plugin. I am making to work with multiple forms on a page. when the form is submitted it is validated. The problem I am having is that in the plugin I can loo through the elements of the form but in the .submit I can only access the last form of the set sent to j!uery. my html is 2 forms. on has an input with a name of num and the other has one named alpha. they both have their own submit button. below is the main section of the jQuery plugin. for the plugin in am simply sending it form. o.attr is stores the name of the attribute with the validation rules.
var options = $.extend(defaults, options);
return this.each(function()
{
form=this;
var o = options;
//this gets me both inputs on page load
$('['+o.attr+']', form).each(function()
{
var val=$(this).val()
alert($(this).attr('name'))
})
//on submit It will alert the last forms input regardless of what form i submited
$(this).submit(function()
{
var o = options;
$('['+o.attr+']', form).each(function()
{
var val=$(this).val()
alert($(this).attr('name'))
})
return false;
})
});
You forgot to declare your form
var, so it’s an accidental global variable and not captured in a closure as you expected.Consequently by the time the
submitfunction is calledformwill always hold the last value ofthisregardless of which form was submitted.(Use a lint tool on your code, or an ECMAScript Fith Edition Strict Mode-supporting browser, to detect accidental globals.)