Reputation: 847
I have a page that in different sections contains the same form twice—a simple, single input field to enter an email address. I have the following submit
function configured, and I'm wondering about the simplest route for allowing the two forms to behave independently of one another; for as I have it configured now, both forms are effectively treated by the script as a single entity. Is there a way to specify to submit the nearest or active form within the .form
div? Or should I configure the submit function in an entirely different way? Thanks for any insight here.
$(document).ready(function() {
var infoForm = $('.form form');
var formSuccessMsg = $('p.success');
var formErrorMsg = $('p.error');
infoForm.submit(function() {
// var url = $(this).attr('action');
var url = $(this).attr('action') + '?showtemplate=false';
var emailInput = $('.form input[type=text]').val();
var data = $(this).serialize();
if( emailInput.length === 0 || emailInput == '' || !isValidEmailAddress(emailInput) ) {
formErrorMsg.show();
return false;
} else {
$.post(url, data, function(data, textStatus, jqXHR) {
// alert('post came back');
infoForm.hide();
formErrorMsg.hide();
formSuccessMsg.show();
console.log(emailInput);
});
return false;
}
});
});
Update: And here is the markup (form code is generated by a CMS):
<div class="form">
<div class="form-response">
<p class="success">Thank you!</p>
<p class="error">Please enter a valid email address</p>
</div>
<form id="mc2e7cmoduleform_1" method="post" action="post" enctype="multipart/form-data">
<div class="info-packet-form">
<div class="required"><input type="text" name="mc2e7cfbrp__35" value="" size="25" maxlength="80" id="fbrp__35" /></div>
<div class="submit"><input name="mc2e7cfbrp_submit" id="mc2e7cfbrp_submit" value="Submit" type="submit" class="fbsubmit" /></div>
</div>
</form>
</div>
Upvotes: 0
Views: 333
Reputation: 535
$(document).ready(function() {
var infoForm = $('.form form');
infoForm.submit(function() {
// create a var to reference this specific form
var $thisForm = $(this);
// assuming you want to only show the messages nearest to your form,
// you can select the parent div and find the response divs in there too.
// create a reference to the specific parent div (div class="form")
var $parent = $thisForm.parent();
// these will reference the specific fields specific to this form
var formSuccessMsg = $parent.find('p.success');
var formErrorMsg = $parent.find('p.error');
var url = $thisForm.attr('action') + '?showtemplate=false';
var emailInput = $thisForm.find('input[type=text]').val();
if( emailInput.length === 0 || emailInput == '' || !isValidEmailAddress(emailInput) ) {
formErrorMsg.show();
return false;
} else {
$.post(url, $thisForm.serialize(), function(data, textStatus, jqXHR) {
// alert('post came back');
$thisForm.hide();
formErrorMsg.hide();
formSuccessMsg.show();
console.log(emailInput);
});
return false;
}
});
});
Upvotes: 2