0

I'm new with jquery. I want to display an error message when the entry is not a number. The problem here when the user deletes the inputs and correctly writes a number, the error message will still appears . How I can solve this problem ?

$("#SpecCode").mousedown( function() {
    specialismCode=$(this).val();
    if (!$.isNumeric(specialismCode) || specialismCode.length !=''){
        $("#SpecCode").parent().after('<span class="validation">Please enter correct input</span>');
        }

        });
3
  • Why would a length ever be equal to '' (a string)? Commented Aug 24, 2017 at 18:18
  • if not, the error message will appears before the user touch the keyboard Commented Aug 24, 2017 at 18:21
  • .length returns a number. If there is no length, it returns 0 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 24, 2017 at 18:22

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works. Obviously, I need to spend more time on jquery to learn it perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.