$(document).ready(function(){
$("form").submit(function(e) {
e.preventDefault();
var empty_count = 0;
$('.required').each(function() {
if ($(this).val() === '') {
empty_count++;
console.log($(this).val());
$(this).addClass('error');
}
else {
$(this).removeClass('error');
}
});
console.log(empty_count);
if (!empty_count) {
$("form").submit();
}
});
});
.error {
border-width:2px;
border-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h2>User Registration</h2>
<form id='user-register' action='/user-register.php' method='post' enctype="multipart/form-data">
<input type='text' name='first_name' class="required" placeholder=''/><br><br>
<input type='text' name='last_name' class="required" placeholder=''/><br><br>
<input type='email' name='email' class="required" placeholder=''/><br><br>
<label>Profile Photo<br></label>
<input type="file"
id="user_profile_photo" name="user_profile_photo"
accept="image/png, image/jpeg, image/jpg"><br><br>
<!-- <input type='submit' name='file_submit'/><br><br> -->
<input class="required" type='password' name='password' placeholder='*****'/><br><br>
<input class="required" type='password' name='confirm_password' placeholder='*****'/><br><br>
<input type='submit' name='register'/><br><br>
</form>
</div>
I have implemented a code to show red colored border around fields which are empty and using jquery code as seen above but it leads to loop. How can I fix it ?