JQuery Dynamically adding a element and then updating it

I'm trying to do a little script to insert after a textbox or textarea how many characters the user has used and whats remaining. In order to do this I'm looking for DOM objects that have the MVC3 added data- validation.

I want my JQuery script to insert a tag automatically after the textbox and then update it after every keypress. I can get it to insert the tag but I can't work out how to get it to update it. I've added the code below:

// controls character input/counter
$("[data-val-length-max]").keyup(function (e) {
var $this = $(this),
    charLength = $this.val().length,
    charLimit = $this.attr("data-val-length-max");
// Displays count
var $chars = $this.nextAll("<span>");

if ($chars != "null") {
    $chars.html(charLength + " of " + charLimit + " characters used");
}
else {
    $this.after("<span>" + charLength + " of " + charLimit + " characters used" + "</span>").addClass("block");
}
// Alert when max is reached
//    if ($this.val().length > charLimit) {
//        $this.nextAll("span").html("<strong>You may only have up to " + charLimit + " characters.</strong>");
//    }
});

I'm still very new to JQuery to I apologise at what is probably some poor coding! Its probably worth stating that there will be multiple instances of character limited textboxes to a single page so the script needs to make sure it only adds/updates the span for its self not any other elements.

Answers


Change your if condition:

$chars != "null"
$chars.size() // size returns 0 if it found no elements

I got it working by fixing some other problems for you in this fiddle: http://jsfiddle.net/mAMM5/1/


Need Your Help

jsf 1.2 popup dialogue box on delete button press

primefaces jsf-1.2

I need to have a confirmation dialogue box onclick of a delete button. I am using Jsf 1.2 can I use primeFace or RichFaces to do it? or what is the approch?

how to increase speed of timer object using swift

ios iphone swift xcode6

I am using an "NSTimer.scheduledTimerWithTimeInterval" object but cannot increase the speed of the clock to faster than 1/1000. I have tried invalidating the clock and re-creating. timer2 &amp; tim...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.