开发者

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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜