So I want to do a validate function using jquery for a school assignment which makes sure that no fields are left empty on the click of the submit button. I did the code below but it doesn't seem to be working. Any ideas? Thanks
$(document).click(function () {
var name = $("#firstname").val();
var surname = $("#lastname").val();
var email = $("#email").val();
var comment = $("#comment").val();
if(name=="" || surname=="" || email=="" || comment==""){
alert("A field is missing");
} else {
return true;
}
});
Edit 1: I change the first line so I made it .submit instead:
$('#valForm').submit(function(){
Edit 2: JS Code:
$(document).ready(function () {
$('#valForm').submit(function () {
var name = $("#firstname").val();
var surname = $("#lastname").val();
var email = $("#email").val();
var comment = $("#comment").val();
if (!name || !surname || !email || !comment) {
alert("A field is missing");
e.preventDefault();
return false;
} else {
return true;
}
})
});
Html Code:(Don't mind the indentation)
<div id="question-box">
<form onsubmit="checkEmail()" id="valForm">
<h2>Contact the club</h2>
<label for="">First Name:</label>
<input type="text" name="firstname" id="firstname" placeholder="First Name"/>
<br>
<br>
<br>
<label for="">Last Name:</label>
<input type="text" name="lastname" id="lastname" placeholder="Last Name"/>
<br>
<br>
<br>
<label for="">Email:</label>
<input type="text" name="email" id="email" placeholder="email"/>
<br>
<br>
<br>
<label for="">Comments:
<br>
<br>
<br>
<br>
</label>
<input type="text" name="comments" id="comment">
<br>
<br>
<br>
<input type="submit" value="submit" id="submit">
</form>
</div>
Ok it worked. Stupid mistake as usual...wasn't calling the script plugin where I was supposed to. Thanks all for your patience <3
$('#my_form_id').submit(function(){?