ANSWER UPDATE
If you need to show/hide the validation message you can add it directly to the html fragment and use the .toggle(true/false).
$("#SpecCode").on('input', function(e) {
var specialismCode = $(this).val();
var nextele = $(this).next('span');
nextele.toggle(!$.isNumeric(specialismCode) || specialismCode.length == 0);
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="SpecCode">Number:
<input type="text" id="SpecCode"><span class="validation">Please enter correct input</span>
</label>
</form>
You have some issues in your code.
Instead of:
specialismCode.length !=''
you can use:
specialismCode.length == 0
Instead of mousedown you can use input.
Finally, the error message comes after the input field. So, you can use:
$(this).next('span')
in order to select the error message.
The snippet:
$("#SpecCode").on('input', function(e) {
var specialismCode = $(this).val();
var nextele = $(this).next('span');
if (!$.isNumeric(specialismCode) || specialismCode.length == 0) {
$(this).after(function(idx, txt) {
return (nextele.length == 0) ? '<span class="validation">Please enter correct input</span>' : '';
});
} else {
nextele.remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="SpecCode">Number:
<input type="text" id="SpecCode">
</label>
</form>
''(a string)?.lengthreturns a number. If there is no length, it returns0developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…