1

I want to add <em> tag after textbox, if user inserted non-numeric format.

$('.numeric').keypress(function (e) {
 var key_code = e.which;
 if (key_code != 8 && key_code != 0 && (key_code < 48 || key_code > 57)) {
    $(this).after("<em>type only numeric formatted text<em>");
    return false ;
 }
 else {
    $('em').remove();
 }
});

Textboxes more than one. HTML code:

<div>
    <label for="Area">Full Area:</label>
    <input type="text" value="" name="FullArea" id="FullArea" class="numeric">
</div>

In my jQuery code have some issues:

  1. Will add <em> more than one time, after non-numeric format;

  2. Will remove all <em> tag, if user typed numeric format (near other textboxes too, all em in page)

Need smart way to do this functionality, without issues [1] and [2]. Thanks.

3 Answers 3

2

I would suggest to just hide and show that,... it's much cheaper than removing and adding again...

try this demo

var em = $("<em>type only numeric formatted text<em>").hide();
$('.numeric').keypress(function (e) {
    var key_code = e.which;
    if (key_code != 8 && key_code != 0 && (key_code < 48 || key_code > 57)) {
       $(this).next("em").show();
       return false ;
    }
    else {
       $(this).next("em").hide();
    }
}).after(em);
Sign up to request clarification or add additional context in comments.

1 Comment

@loviji - yes... and it still works as expected... much cheaper than add-remove way... please see demo...
1

Try this:

('.numeric').keypress(function (e) { 
 var next = $(this).next('em');
 var key_code = e.which; 
 if (key_code != 8 && key_code != 0 && (key_code < 48 || key_code > 57)) { 
    if (next.length == 0)
        $(this).after("<em>type only numeric formatted text<em>"); 
    return false ; 
 } 
 else { 
    next.remove(); 
 } 
}); 

Comments

0

Take a look at the jQuery Validation Plugin that will do exactly this (and much more!) for you.

The real strength of jQuery is its pluggability, and the fact that there are so many plugins already written. If someone else has already invented the wheel, save some time and use theirs ;)

Comments

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.