loviji
loviji

Reputation: 13080

jQuery add content after input element and remove added content

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.

Upvotes: 1

Views: 2353

Answers (3)

Tomas Aschan
Tomas Aschan

Reputation: 60564

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 ;)

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

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);

Upvotes: 2

Matt Mitchell
Matt Mitchell

Reputation: 41823

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(); 
 } 
}); 

Upvotes: 1

Related Questions