gpt4 book ai didi

javascript - jQuery:同一页面上两个相同表单的提交功能

转载 作者:行者123 更新时间:2023-12-03 02:29:06 25 4
gpt4 key购买 nike

我有一个页面,在不同部分中两次包含相同的表单 - 一个简单的单个输入字段,用于输入电子邮件地址。我配置了以下 submit 函数,并且我想知道允许两种表单彼此独立运行的最简单途径;因为正如我现在配置的那样,两种形式都被脚本有效地视为单个实体。有没有办法指定在 .form div 内提交最近事件表单?或者我应该以完全不同的方式配置提交功能?感谢您在这里提供任何见解。

$(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;
}
});
});

更新:这是标记(表单代码由 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>

最佳答案

$(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;
}
});
});

关于javascript - jQuery:同一页面上两个相同表单的提交功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48813015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com