根据标题,我想通过单击span元素来提交表单。我还想阻止页面刷新。我还想为手机视图添加普通的提交按钮。但是,除非我直接提交表单,否则提交是不起作用的。当我点击span元素时,有没有办法用ajax提交表单?我还知道,在表单中提交elemnt可能会给向php发送数据带来麻烦。那么,有办法解决这个问题吗?我的代码-
HTML
<div class="row">
<div class="col">
<form action="" class="w-50 m-lg-0 m-auto" id="contactForm">
<label for="name" class="change text-white minor- text-white change font mb-2">Your Name</label>
<input type="text" name="name" class="form text-white change bg-color" id="name" required><br>
<label for="email" class="change text-white minor-font text-white change mb-2">Email</label>
<input type="email" name="email" class="form text-white change bg-color" id="email" required><br>
<label for="subject"class="change text-white minor-font text-white change mb-2">Subject</label>
<textarea class="form bg-color text-white change" name="subject" id="subject" required></textarea>
<input type="submit" class="btn btn-outline-light title-font mt-5 w-75 m-auto m-lg-0 mt-lg-5 d-block" id="send" value="Send">
</form>
</div>
<div class="col-12 col-md 6 col-lg-4 d-xl-block d-none">
<div class="parent">
<img src="photos/cloud.png" alt="cloud" class="cloud" width="700px">
<span class="change text-white fs-1 pos" id="paper">
<i class="fa-regular fa-paper-plane"></i>
</span>
</div>
</div>
</div>
Jquery
$("#paper").on("click", function () {
$("#contactForm").validate();
console.log("good")
$("#contactForm").on("submit", function (e) {
e.preventDefault();
var dataString = $(this).serialize();
console.log("nice")
$.ajax({
type: "POST",
url: "_actions/sendmail.php",
data: dataString,
success: function () {
console.log("best")
$("#paper").addClass("posRun");
}
});
return false;
});
});
永远不要在其他事件回调中添加其他事件!
你应该只在点击时触发子弹,而不是添加事件:
$(document).on("click", "#paper", function () {
$("#contactForm").validate({
submitHandler: function(form) {
console.log("good");
form.submit();
}
});
});
$(document).on("submit", "#contactForm", function (e) {
e.preventDefault();
var dataString = $(this).serialize();
console.log("nice")
$.ajax({
type: "POST",
url: "_actions/sendmail.php",
data: dataString,
success: function () {
console.log("best")
$("#paper").addClass("posRun");
}
});
return false;
});