I am attempting to use jQuery Validate's errorPlacement
function to place an error message, but I cannot figure it out. Whenever I hit submit, the input slides down, instead of the error placing in the newsletterValidate
div.
Does anyone see what I am doing wrong in my errorPlacement
code?
$('#newsletterForm').validate({
//errorClass: 'invalid',
errorPlacement: function(error, element) {
//element.val(error[0].outerText);
//error.appendTo(element.next('div'));
error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
},
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#newsletterForm').serialize();
$.ajax({
url: 'http://localhost:8080/php/newsletterSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
alert(data);
} else {
$('#newsletterInput')[0].reset();
$('#newsletterSuccess').show();
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
#newsletterInput {
width: 70%;
border: none;
padding: 15px 10px;
outline: none;
font-size: 1.1rem;
font-family: 'Nunito', sans-serif;
display: inline-block;
background: pink;
}
#newsletterSubmit {
width: 25%;
display: inline-block;
border: none;
font-size: 1.1rem;
font-family: 'Nunito', sans-serif;
padding: 15px 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<div>
<form id="newsletterForm">
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</form>
</div>
<div id="newsletterValidate"></div>