Issue
I have the following HTML and jQuery code
$("#addNeedleButton").click(function() {
var needle = $("#needleName").val();
needle = needle.trim();
if (needle.length == 0) {
$("#addNeedleManagement").submit(function(e) {
e.preventDefault();
er("Please key in a Needle Type");
});
}
});
function er($message){
var errorDisplay = $message;
$("#errorDisplay").html(`<strong>Error </strong>${errorDisplay}`);
$('#errorDisplay').show();
$("#errorDisplay").fadeTo(2000, 1000).slideUp(1000, function(){
$("#errorDisplay").slideUp(1000);
});
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<form method="post" id="addNeedleManagement" name="addNeedleManagement">
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="addNeedle">Needle Type</label>
<input type="text" class="form-control" id="needleName" name="needleName" placeholder="New needle name" title="Please key in the new needle name" required>
</div>
</div>
</div>
<button type="submit" id="addNeedleButton" name="addNeedleButton" class="btn btn-primary">Add Needle</button>
</form>
What I need is to prevent form submission if the input field is empty or it contains only white spaces. But somehow this code is not working. If I didn't key in anything, then it supposed to show the error message. But it is not triggering. If I put empty spaces, then it is working correctly by calling the error message. But if I keyed in some string, the error message still popping out.
Does anyone know why?
Solution
Change your code to this
<form method="post" id="addNeedleManagement" name="addNeedleManagement">
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="addNeedle">Needle Type</label>
<input type="text" class="form-control" id="needleName" name="needleName" placeholder="New needle name" title="Please key in the new needle name">
</div>
</div>
</div>
<button type="button" id="addNeedleButton" name="addNeedleButton" class="btn btn-primary">Add Needle</button>
</form>
Your script is
<script>
$("#addNeedleButton").click(function(e) {
var needle = $("#needleName").val();
needle = needle.trim();
if (needle.length == 0) {
er("Please key in a Needle Type");
return false
} else {
$('#addNeedleManagement').submit();
}
});
function er($message) {
var errorDisplay = $message;
$("#errorDisplay").html(`<strong>Error </strong>${errorDisplay}`);
$('#errorDisplay').show();
$("#errorDisplay").fadeTo(2000, 1000).slideUp(1000, function() {
$("#errorDisplay").slideUp(1000);
});
}
Answered By - Qonvex620
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.