I am trying to write a jquery(ajax) code that check some fields in the html form for validation before submit and also if any error occurs the message must display in the div with id response but it is not working.
$(document).ready(function() {
$('form #response').hide(); //hide the response div in the html
$('#create').click(function(e) {
e.preventDefault(); //stop the form from submitting
var valid = '';
var required = ' is required';
var name = $('form #fname').val();
var email = $('form #email').val();
var username $('form #username').val();
var pword = $('form #password').val();
if (name == '' || name.length <= 2) {
valid = '<p>Your name ' + required + '</p>';
}
if (!email.match(/^([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email ' + required
}
if (username == '' || username.length <= 2) {
valid += '<p>A username ' + required + '</p>';
}
if (pword == '') {
valid += '<p>A username ' + required + '</p>';
}
if (valid != '') {
$('form #response').removeClass().addClass('error')
.html('<strong>Please correct the errors below.</strong>' + valid).fadeIn('fast');
}
}); //click function
}); //ready function
#response {
border: 1px solid #FF0000;
color: #333;
height: auto;
min-height: 45px;
width: 100%;
margin-bottom: 20px;
}
#response p {
margin: 0;
padding: 0;
}
.error {
background: #FF9F9F url(img/alert.png) no-repeat 5px 10px;
}
<form id="createForm" name="theForm" method="post" action="createUser.php">
<legend><span class="icon"><img src="/registerUser/img/createIcon.png"></span> Create New User</legend>
<p><span id="requiredfields">* required field.</span>
</p>
<!--<span id="errorMessage"> </span>-->
<div id="response">
<!--This will hold the message and the response from the server-->
</div>
<input id="fname" type="text" name="fname" placeholder="Name *" pattern="^[A-Za-z ]+$">
<br>
<br>
<input id="email" type="email" name="email" placeholder="Email *" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">
<br>
<br>
<input id="username" type="text" name="username" placeholder="Username *">
<br>
<br>
<input id="password" type="password" name="password" placeholder="Password *">
<br>
<br>
<label for="roles">Roles:</label>
<select id="role" name="roles">
<option>Select Role</option>
<option value="empty"></option>
<option value="Reporter">Reporter</option>
<option value="Lover">Lover</option>
<option value="Other">Other</option>
</select>
<br>
<br>
<input id="create" type="submit" name="createUser" value="Create User">
</form>
</div>