I have an HTML page with an e-mail submission form. I need to check on the same page whether the fields were filled out or not at the time the user clicks the Submit button. Apparently it is bypassing the javascript function and it is sending the email regardless of the content of the form.
Follow the script.js with the function and then index.html.
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var nome = document.getElementById("nome").value;
var email = document.getElementById("email1").value;
var fone = document.getElementById("telefone").value;
var mensagem = document.getElementById("mensagem").value;
//Check input Fields Should not be blanks.
if (nome == '' || email == '' || fone == '' || mensagem == '') {
alert("Por favor preencha todos os campos.");
} else {
//Notifying error fields
var name = document.getElementById("nome");
var mail = document.getElementById("email");
var telefone = document.getElementById("telefone");
var mensagemp = document.getElementById("mensagem");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (name.innerHTML == 'Nome' || mail.innerHTML == 'E-mail' || telefone.innerHTML == 'Telefone' || mensagemp.innerHTML == 'Sua Mensagem') {
alert("Por favor, preencha o formulário com informações válidas");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<form method="post" action="sendmail.php">
<input type="text" class="text" value="Nome" name="nome" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Nome';}">
<input type="text" class="text" value="E-mail" name="email" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-mail';}">
<input type="text" class="text" value="Telefone" name="telefone" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Telefone';}">
<textarea name="mensagem" required onfocus="if(this.value == 'Sua mensagem') this.value='';" onblur="if(this.value == '') this.value='Sua mensagem';" >Sua mensagem</textarea>
<input type="submit" value="[ Enviar Mensagem ]" onclick="checkForm()" />
</form>
</body>
</html>
sendmail.php
<?php
$to = '[email protected]';
$subject = 'Contato Site';
$message = "Nome: ".$_POST['nome']."\r\nE-mail: ".$_POST['email']."\r\nTelefone: ".$_POST['telefone']."\r\n\r\nMensagem:\r\n".$_POST['mensagem']."\r\n\r\n";
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
header("Location: http://www.site.com.br/obrigado.html");
die();
?>