Now I know this sounds elementary, but I honestly can’t dial this in. I have two forms on a single page. I wrote some form validating functions that are triggered as such:
$("form").submit(function(event) {
event.preventDefault();
checkRequired();
checkLengths();
checkFormats();
checkErrors();
});
This is awesome, but inside the functions, I cannot use $(this) to identify the <form> from which the submit button was clicked.
Let’s say I wrote alert($(this).attr('id')); in the checkRequired() function. It alerts “Object, object“.
If I place the same code inside the $("form").submit() function, it returns my form’s id.
The selectors inside the functions are things like $("input[type='text']") and similar, but the functions run on all the inputs, not just the ones in the form that was submitted.
Sample function() used:
function checkFormats() {
alert("Checking Formats...");
$(".email").each(function(){
alert("Checking Formats: Email...");
var emailField = $(this).children("input[type='text']");
var strEmail = emailField.val();
if( strEmail.indexOf( "@" ) == -1 ) {
alert("What the hell?");
}
});
}
I’m sure I’ll feel dumb when I hear the solution, but hey, I’m overly-tired lol… Thanks in advance!
Thinking maybe $("form",this) may get me somewhere?
Can you not pass the form to the methods?
Then you have the right context.
You can now select any additional elements within the context of the specified form, similar to this::
Alternative – Use JavaScript .apply
(As mentioned by Mike Robinson in the comments)
Then
thiswithin the function becomes the form. You can now use it like this:DEMO – Using
.applyDemo uses a simple HTML From:
With this script: