Reputation: 89
Below is my code. What I want to do is add validation so when the user clicks off an input field the validation message "name required" shows up. However at the minute it is just below the input field and is there all the time. Thank you
$(document).ready(function(){
if($('#firstname').val() == ''){
$('.errorMsg').show();
} else{
$('.errorMsg').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First name" maxlength="15" <span class="errorMsg">Name required </span>
</input>
Upvotes: 1
Views: 50
Reputation: 1
jQuery Blur - Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
Try (JSFiddle)
var firstNameInput = $('input#firstname'),
errorMsgEl = $('.errorMsg');
// Bind blur on the input for 'first name'
firstNameInput.bind('blur', function () {
// Check if input is blank
if(firstNameInput.val() == '') {
// Ensure error isn't already displayed
if (errorMsgEl.length == 0) $("<div class='errorMsg'>Name required</div>").insertAfter(this);
} else {
errorMsgEl.remove();
}
});
Upvotes: 0
Reputation: 2289
Use CSS to initially hide the error-message. You also have invalid HTML: the error-message span
can't be nested in the input.
Working solution:
$(document).ready(function(){
$('#firstname').on('blur', function() {
if($(this).val() === '') {
$('.errorMsg').show();
} else {
$('.errorMsg').hide();
}
});
});
.errorMsg {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First name"
maxlength="15"/>
<span class="errorMsg">Name required </span>
Upvotes: 1
Reputation: 278
Use blur
event, which can be called directly from the found element using jQuery
$(document).ready(function(){
$('.errorMsg').hide();
$('#firstname').blur(function(){
if($('#firstname').val() == ''){
$('.errorMsg').show();
}
else{
$('.errorMsg').hide();
}
});
});
Here's a JSFiddle
Upvotes: 0
Reputation: 6868
You can use the blur
event for that:
$(document).ready(function() {
$('#firstname').on('blur', function() {
if ($('#firstname').val() == '') {
$('.errorMsg').show();
} else {
$('.errorMsg').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First name"
maxlength="15"> <span class="errorMsg" style="display: none;">Name required </span>
</input>
Upvotes: 0