To achieve the desired functionality, you can add the following pure JavaScript code to your webpage. This code adds an event listener to the form, intercepts the form submission, validates the required fields, constructs a mailto: link with the specified email content, and then simulates a click on that link to open the user's default mail client.
Here's the JavaScript code:
document.addEventListener('DOMContentLoaded', function() {
var form = document.querySelector('form.style-0');
form.addEventListener('submit', function(event) {
event.preventDefault();
// Get the form data
var nome = form.querySelector('input[name="zen_name"]').value.trim();
var email = form.querySelector('input[name="zen_email"]').value.trim();
var subject = form.querySelector('input[name="zen_subject"]').value.trim();
var message = form.querySelector('textarea[name="zen_desc"]').value.trim();
// Validate required fields
if (!nome || !email || !subject || !message) {
alert('Per favore, compila tutti i campi obbligatori.');
return;
}
// Build the mailto link
var toEmail = 'tobedefined@email.com';
var mailSubject = 'Richiesta di Informazioni';
var mailBody = 'Salve,\r\nSono interessato a discutere una possibile collaborazione con la vostra azienda. Quando sarebbe disponibile per una chiamata?\r\nCordiali saluti,\r\n' + nome;
var mailtoLink = 'mailto:' + encodeURIComponent(toEmail) +
'?subject=' + encodeURIComponent(mailSubject) +
'&body=' + encodeURIComponent(mailBody);
// Simulate click on mailto link
window.location.href = mailtoLink;
});
});
Explanation:
-
Event Listener Setup: The code waits for the DOM content to load and then selects the form using document.querySelector('form.style-0'). An event listener is added to the form to handle the submit event.
-
Prevent Default Submission: event.preventDefault(); stops the form from submitting the traditional way.
-
Data Retrieval and Validation: The script retrieves the values of the required fields. If any of the required fields are empty, it alerts the user and stops execution.
-
Construct Mailto Link:
- Sets the recipient email (
toEmail) to tobedefined@email.com.
- Sets a fixed subject (
mailSubject) as specified.
- Prepares the email body (
mailBody), inserting the user's name in place of [Il tuo nome].
- Uses
encodeURIComponent to properly encode the subject and body for use in a URL.
-
Simulate Mailto Link Click: Updates window.location.href to the constructed mailto: link, prompting the user's email client to open a new message with the specified content.
Note: Make sure to include this script after the form in your HTML or within the <head> tag if you are using DOMContentLoaded to ensure the elements are available when the script runs.