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.

loviji
  • 12,620
  • 17
  • 63
  • 94

3 Answers3

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);
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
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(); 
 } 
}); 
Matt Mitchell
  • 40,943
  • 35
  • 118
  • 185
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 ;)

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402