As from the title, I want to submit a form by click a span element. I also want to prevent the page from refreshing. I also want to add normal submit button for mobile view. But on submit won’t work unless I directly submit the form. Is there a way to submit the form with ajax when I hit the span element? I also know that having submit elemnt in form might give trouble to sending data to php. So, is there a way to resolve this?
My code –
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;
});
});
>Solution :
Never add additional events inside other event callback!
You should just trigger form submunition on click, not add event:
$(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;
});