As of lately I have become, well, obsessed with the Prototype JavaScript library. There is, as there always is, heated discussions across the internet of the benefits/strengths/weaknesses of many readily-available JavaScript libraries.
Such as:
But for the time being, all those libraries are irrelevant. It’s great how easy they are to use, but what fun is it if you don’t know enough JavaScript to edit those libraries. Still probably very fun, but let’s get our hands dirty with JavaScript today!
The way these libraries work depends on extending the prebuilt JavaScript objects.
Typically when you create a function for JavaScript you’d do something like this:
trim_func function(value) {
return value.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}
And then you would use it like this:
// this would be used, probably in an input text field onBlur
trim_func(this.value);
trim_func(' hello my dear world . '); // returns 'hello my dear world .'
By extending the library either of the two following ways
// method 1
String.prototype.trim = function() {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}
//method 2
trim_func function(this) {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}
String.prototype.trim=trim_func;
And you can use either of those two methods extending the String object like so:
this.value.trim();
Which is a beautiful thing when quickly and easily applied to a input field:
<input type="text" name="lname" id="lname" value="" title="Please enter your last name" onchange="this.value=this.value.trim();" />
So go throw one of the methods of trim to your library.js file and use it on your forms. It’s great for trimming down values (so your server side script isn’t the only one doing it) and also removing entries that are solely spaces to help with validation.
Check out The Prototype Property of JavaScript 1.1 on JavaScriptKit.com for more information!