OffBeatMammal

Searching for monkeys in Cyberspace

MaxLength on a Textarea

clock October 26, 2006 11:14 by author offbeatmammal

Although HTML is very clever (and there are lots of very clever things hidden if you go looking) there's one thing that's bugged me since I first started putting forms together in a webpage.

Why is there a maxlenth parameter on an <input type="text"....> field but no maxlength attribute on a <textarea....>....</textarea>

Now I know it's possible to write some javascript and attach it to a text area that you want and control user input that way. But it requires thought and effort and it's not a very elegant solution.

But, as you can see... the problem can be solved:

I came across the concept of CSS behaviours (or is that behaviors) thanks to a really handy script 'behaviours.js' from Ben Nolan which allows you to assign a behaviour to a CSS rule. I then applied that to allow me to add a couple of extra attributes to the Textarea HTML tag. Specifically the Maxlength and showremain function. Adding them to a page is as easy as this (the hardest bit it to remember to include the two scripts!)

<html> <head> <script type="text/javascript" src="/scripts/behaviour.js"></script> <script type="text/javascript" src="/scripts/textarea_maxlen.js"></script> </head> <body> <p>Limit 120 Characters: <TEXTAREA rows="5" cols="30" maxlength="120" showremain="limitOne"></TEXTAREA> <br>Chars Remaining:<span id="limitOne">--</span></p> <p>Limit 50 Characters: <TEXTAREA rows="2" cols="30" maxlength="50" showremain="limitTwo"></TEXTAREA> <br>Chars Remaining:<span id="limitTwo">--</span></p> </body> </html>

 The logic to check the length of the selected object, enforce it and (if required) update the span showing the remaining characters is within the textarea_maxlen script. It registers functions against the onkeydown, onkeyup, onpaste and onblur methods for the CSS textarea attribute.

var CSSrules = { 'textarea' : function(element){ element.onkeydown = function(event){ return doKeyPress(element,event); } , element.onpaste = function(){ return doPaste(element); } , element.onkeyup = function(){ return doKeyUp(element); } , element.onblur = function(){ return doKeyUp(element); } } } Behaviour.register(CSSrules);

the actual javascript to check and enforce the length and update the progress is all pretty standard stuff - in fact, it's probably not that elegant but it was more a case of getting it working in a hurry and having it work in IE (PC), FireFox (PC, OSX and Ubuntu) and Safari (OSX) - the test platforms for the project (if you can tidy it up, please leave a comment here!) The biggest problem I encountered was the different event handling models for IE and Gecko based browsers - both in when events were triggered and how to stop them bubbling further!

var detect = navigator.userAgent.toLowerCase(); // Keep user from entering more than maxLength characters function doKeyPress(obj,evt){ maxLength = obj.getAttribute("maxlength"); var e = window.event ? event.keyCode : evt.which; if ( (e == 32) || (e == 13) || (e > 47)) { //IE if(maxLength && (obj.value.length > maxLength-1)) { if (window.event) { window.event.returnValue = null; } else { evt.cancelDefault; return false; } } } } function doKeyUp(obj){ maxLength = obj.getAttribute("maxlength"); if(maxLength && obj.value.length > maxLength){ obj.value = obj.value.substr(0,maxLength); } sr = obj.getAttribute("showremain"); if (sr) { document.getElementById(sr).innerText = maxLength-obj.value.length; } } // Cancel default behavior and create a new paste routine function doPaste(obj){ maxLength = obj.getAttribute("maxlength"); if(maxLength){ if ((window.event) && (detect.indexOf("safari") + 1 == 0)) { //IE var oTR = obj.document.selection.createRange(); var iInsertLength = maxLength - obj.value.length + oTR.text.length; try { var sData = window.clipboardData.getData("Text").substr(0,iInsertLength); oTR.text = sData; } catch (err) { } if (window.event) { //IE window.event.returnValue = null; } else { //not IE obj.value = obj.value.substr(0,maxLength); return false; } } } }

In order for this to work in your own page remember: you must go and download the behaviour.js file from Bens site, and the textarea_maxlen.js script from here.

With a bit more imagination and time you could extend this to enforce rules like MaxLength="500" MaxWords="150" to lock down how much data can be entered, or MaxCaps="15%" to stop them SHOUTING.

The maxlength attribute is part of a proposed HTML5 standard, but it'll be interesting to see if we ever get there with the directions devolving to XHTML and microformats an rich internet application technologies such as WPF/E.



MaxLength on a Textarea

clock October 26, 2006 11:14 by author OffBeatMammal

Although HTML is very clever (and there are lots of very clever things hidden if you go looking) there's one thing that's bugged me since I first started putting forms together in a webpage.

Why is there a maxlenth parameter on an <input type="text"....> field but no maxlength attribute on a <textarea....>....</textarea>

Now I know it's possible to write some javascript and attach it to a text area that you want and control user input that way. But it requires thought and effort and it's not a very elegant solution.

But, as you can see... the problem can be solved:

I came across the concept of CSS behaviours (or is that behaviors) thanks to a really handy script 'behaviours.js' from Ben Nolan which allows you to assign a behaviour to a CSS rule. I then applied that to allow me to add a couple of extra attributes to the Textarea HTML tag. Specifically the Maxlength and showremain function. Adding them to a page is as easy as this (the hardest bit it to remember to include the two scripts!)

<html><head><script type="text/javascript" src="/scripts/behaviour.js"></script><script type="text/javascript" src="/scripts/textarea_maxlen.js"></script></head><body><p>Limit 120 Characters: <TEXTAREA rows="5" cols="30" maxlength="120" showremain="limitOne"></TEXTAREA> <br>Chars Remaining:<span id="limitOne">--</span></p><p>Limit 50 Characters: <TEXTAREA rows="2" cols="30" maxlength="50" showremain="limitTwo"></TEXTAREA> <br>Chars Remaining:<span id="limitTwo">--</span></p></body></html>

 The logic to check the length of the selected object, enforce it and (if required) update the span showing the remaining characters is within the textarea_maxlen script. It registers functions against the onkeydown, onkeyup, onpaste and onblur methods for the CSS textarea attribute.

var CSSrules = {
'textarea' : function(element){
element.onkeydown = function(event){
return doKeyPress(element,event);
}
,
element.onpaste = function(){
return doPaste(element);
}
,
element.onkeyup = function(){
return doKeyUp(element);
}
,
element.onblur = function(){
return doKeyUp(element);
}
}
}
 
Behaviour.register(CSSrules);

the actual javascript to check and enforce the length and update the progress is all pretty standard stuff - in fact, it's probably not that elegant but it was more a case of getting it working in a hurry and having it work in IE (PC), FireFox (PC, OSX and Ubuntu) and Safari (OSX) - the test platforms for the project (if you can tidy it up, please leave a comment here!) The biggest problem I encountered was the different event handling models for IE and Gecko based browsers - both in when events were triggered and how to stop them bubbling further!

var detect = navigator.userAgent.toLowerCase();// Keep user from entering more than maxLength characters
function doKeyPress(obj,evt){
maxLength = obj.getAttribute("maxlength");
var e = window.event ? event.keyCode : evt.which;
if ( (e == 32) || (e == 13) || (e > 47)) { //IE
if (maxLength && (obj.value.length > maxLength-1)) {
if (window.event) {
window.event.returnValue = null;
} else {
evt.cancelDefault;
return false;
}
}
}
}
function doKeyUp(obj){
maxLength = obj.getAttribute("maxlength");
if (maxLength && obj.value.length > maxLength){
obj.value = obj.value.substr(0,maxLength);
}
sr = obj.getAttribute("showremain");
if (sr) {
document.getElementById(sr).innerHTML = maxLength-obj.value.length;
}
}
// Cancel default behavior and create a new paste routine
function doPaste(obj){maxLength = obj.getAttribute("maxlength");
if (maxLength){
if ((window.event) && (detect.indexOf("safari") + 1 == 0)) { //IE
var oTR = obj.document.selection.createRange();
var iInsertLength = maxLength - obj.value.length + oTR.text.length;
try {
var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
oTR.text = sData;
}
catch (err) {
}
if (window.event) { //IE
window.event.returnValue = null;
} else {
//not IE
obj.value = obj.value.substr(0,maxLength);
return false;
}
}
}
}

In order for this to work in your own page remember: you must go and download the behaviour.js file from Bens site, and the textarea_maxlen.js script from here.

With a bit more imagination and time you could extend this to enforce rules like MaxLength="500" MaxWords="150" to lock down how much data can be entered, or MaxCaps="15%" to stop them SHOUTING.

The maxlength attribute is part of a proposed HTML5 standard, but it'll be interesting to see if we ever get there with the directions devolving to XHTML and microformats an rich internet application technologies such as Silverlight.



Script debugging in IE

clock September 26, 2006 03:46 by author offbeatmammal

When I'm developing pages that have a lot of JavaScript in, I love Firefox. Ignoring all the hype about why it's better than Internet Explorer it does have one really cool, out of the box debugging tool - the JavaScript Console. It makes tracking problems down so easy. Sure it's a two step process (find the offending error message in the console log, and then look in the source viewer to find the actual line - sometimes a tricky thing when the page is dynamically generated).

But all is not lost in IE. Far from it. Most people when they want to debug JavaScript in IE complain that the only way to do it is to go and buy a copy of Visual Studio. Well, sure, you can do that if you want. But as anyone who's used it to try and debug one typo in a page it can be overkill. Luckily the answer lies in the free (and very small download) MS Script Debugger.

It's integrated with IE (including the latest IE7 betas and release candidate) - when you get a JavaScript error reported on the page just hit "yes" to debug and get taken to the offending line nicely highlit in a source viewer (and if you want to check the source at any time the debugger adds a new item to the "view" menu).

The other toy that makes developing and debugging (JavaScript, HTML, CSS and graphics) in IE a pleasure is the new developers toolbar. This little add-on for IE7 comes with a whole host of goodies from on-screen rulers, a fully featured DOM inspector, the ability to disable browser functions (eg JavaScript or CSS), site level cookie control, highlighting (and detailed information) for any element you might need to examine and even a handy resizer to fit common screen sizes to see how things look.

As a developer currently working on an image,CSS and JavaScript heavy site these tools are invaluable in helping me to deliver what the designer and client want. Give them a quick try and see what you think....



Script debugging in IE

clock September 26, 2006 03:46 by author OffBeatMammal

When I'm developing pages that have a lot of JavaScript in, I love Firefox. Ignoring all the hype about why it's better than Internet Explorer it does have one really cool, out of the box debugging tool - the JavaScript Console. It makes tracking problems down so easy. Sure it's a two step process (find the offending error message in the console log, and then look in the source viewer to find the actual line - sometimes a tricky thing when the page is dynamically generated).

But all is not lost in IE. Far from it. Most people when they want to debug JavaScript in IE complain that the only way to do it is to go and buy a copy of Visual Studio. Well, sure, you can do that if you want. But as anyone who's used it to try and debug one typo in a page it can be overkill. Luckily the answer lies in the free (and very small download) MS Script Debugger.

It's integrated with IE (including the latest IE7 betas and release candidate) - when you get a JavaScript error reported on the page just hit "yes" to debug and get taken to the offending line nicely highlit in a source viewer (and if you want to check the source at any time the debugger adds a new item to the "view" menu).

The other toy that makes developing and debugging (JavaScript, HTML, CSS and graphics) in IE a pleasure is the new developers toolbar. This little add-on for IE7 comes with a whole host of goodies from on-screen rulers, a fully featured DOM inspector, the ability to disable browser functions (eg JavaScript or CSS), site level cookie control, highlighting (and detailed information) for any element you might need to examine and even a handy resizer to fit common screen sizes to see how things look.

As a developer currently working on an image,CSS and JavaScript heavy site these tools are invaluable in helping me to deliver what the designer and client want. Give them a quick try and see what you think....



It's all about performance!

clock September 3, 2006 05:59 by author OffBeatMammal

Just when I think I've got my head around performance tuning for MS SQl Databases, and keeping ASP code trim and sprightly (and even writing PHP scripts that don't suck too badly) ... it turns out I have to start spending a bit more time performance tuning my JavaScripts!

Yup. As Ajax and the Web 2.0 wave start putting a lot more onus on the client to do some of the heavy lifting JavaScript is starting to take on a much larger role in the delivery - and hence performance - of the user experience.

As JavaScript isn't a compiled language (at least, not usually... though there is one to turn JavaScript into Java - which opens up a potential whole new world of hurt!) there are some things you can do manually to ensure your code it well written to reduce reliance on inefficient coding constructs. See this post for more info on things to avoid (and there's 2 more parts to come apparently - I'm scared!) and this article for some more tips on how to do it right.

Once your code is well written there is a further step you can go to - optimisation of the JavaScript source. A few years ago I discovered an awesome little utility (w3compiler from Port80) that makes my JavaScript as lean and mean as it can (and it also works its magic on HTML and CSS source files too)

Happy coding!



It's all about performance!

clock September 3, 2006 05:59 by author offbeatmammal

Just when I think I've got my head around performance tuning for MS SQl Databases, and keeping ASP code trim and sprightly (and even writing PHP scripts that don't suck too badly) ... it turns out I have to start spending a bit more time performance tuning my JavaScripts!

Yup. As Ajax and the Web 2.0 wave start putting a lot more onus on the client to do some of the heavy lifting JavaScript is starting to take on a much larger role in the delivery - and hence performance - of the user experience.

As JavaScript isn't a compiled language (at least, not usually... though there is one to turn JavaScript into Java - which opens up a potential whole new world of hurt!) there are some things you can do manually to ensure your code it well written to reduce reliance on inefficient coding constructs. See this post for more info on things to avoid (and there's 2 more parts to come apparently - I'm scared!) and this article for some more tips on how to do it right.

Once your code is well written there is a further step you can go to - optimisation of the JavaScript source. A few years ago I discovered an awesome little utility (w3compiler from Port80) that makes my JavaScript as lean and mean as it can (and it also works its magic on HTML and CSS source files too)

Happy coding!



IE7 - it won't be mandatory (but you'd have to be mad not to)

clock September 3, 2006 05:34 by author OffBeatMammal

A while ago there were some rumours floating around that IE7 would be a compulsory upgrade for WinXP users. Luckily it turns out that it's not actually mandatory but something that will be recommended by default in Windows Update.

Personally having used IE7 through various beta releases, comparing it to both IE6, Firefox on both the PC and Mac and Safari I have to say any Windows user who chooses not to upgrade really needs to think about why they're not upgrading.

Despite the rhetoric of the usual detractors, the feature list for IE7 is pretty awesome (even leaving aside the marketing hype from the IE7 team!) - improvements to security, stability, rendering, CSS support, Phishing and malware protection and (last but not least) the UI (thank you for Tabs!). The best news is that they've said that IE7 isn't going to be a one-off left to gather dust (like IE6 when Microsoft appeared to decide that they'd won the browser wars and didn't need to bother any more) but the first of a whole series of incremental point releases.

IE7 has dislodged me from Firefox which for about a year was my browser of choice without question on the PC (and neck-and-neck with Safari on OSX) - which is great because I don't have to fire up another browser on the off-chance I'm visiting a site that needs ActiveX (very rare these days admittedly. The only one I use regularly is the excellent eWise account aggregator) or for some reason explicitly checks for IE before letting you in (for some reason less prevalent than the rabid Firefox only sites... but some banks seem to think IE is the only browser out there!)

With IE7 a lot of the reasons to make one of the alternatives the default browser on your system have gone away. IE7 had brought the UI up to a level comparable with the Gecko based browsers, the security - while not perfect - is a lot better (and don't forget... Firefox has had some bad security scares recently as well) and while users get very attached to some of the scripting options available (eg GreaseMonkey) they can open up security risks and display problems with the sites you're visiting!

The only thing that IE7 is missing that annoys me in a big way is a decent JavaScript console / debugger. Gecko based browsers have offered this for years and because my JavaScript is never perfect first time I often need a helping hand (beyond a bunch of alert statements!)... but is it enough to stop me upgrading? Bring it on I say.



IE7 - it won't be mandatory (but you'd have to be mad not to)

clock September 3, 2006 05:34 by author offbeatmammal

A while ago there were some rumours floating around that IE7 would be a compulsory upgrade for WinXP users. Luckily it turns out that it's not actually mandatory but something that will be recommended by default in Windows Update.

Personally having used IE7 through various beta releases, comparing it to both IE6, Firefox on both the PC and Mac and Safari I have to say any Windows user who chooses not to upgrade really needs to think about why they're not upgrading.

Despite the rhetoric of the usual detractors, the feature list for IE7 is pretty awesome (even leaving aside the marketing hype from the IE7 team!) - improvements to security, stability, rendering, CSS support, Phishing and malware protection and (last but not least) the UI (thank you for Tabs!). The best news is that they've said that IE7 isn't going to be a one-off left to gather dust (like IE6 when Microsoft appeared to decide that they'd won the browser wars and didn't need to bother any more) but the first of a whole series of incremental point releases.

IE7 has dislodged me from Firefox which for about a year was my browser of choice without question on the PC (and neck-and-neck with Safari on OSX) - which is great because I don't have to fire up another browser on the off-chance I'm visiting a site that needs ActiveX (very rare these days admittedly. The only one I use regularly is the excellent eWise account aggregator) or for some reason explicitly checks for IE before letting you in (for some reason less prevalent than the rabid Firefox only sites... but some banks seem to think IE is the only browser out there!)

With IE7 a lot of the reasons to make one of the alternatives the default browser on your system have gone away. IE7 had brought the UI up to a level comparable with the Gecko based browsers, the security - while not perfect - is a lot better (and don't forget... Firefox has had some bad security scares recently as well) and while users get very attached to some of the scripting options available (eg GreaseMonkey) they can open up security risks and display problems with the sites you're visiting!

The only thing that IE7 is missing that annoys me in a big way is a decent JavaScript console / debugger. Gecko based browsers have offered this for years and because my JavaScript is never perfect first time I often need a helping hand (beyond a bunch of alert statements!)... but is it enough to stop me upgrading? Bring it on I say.



Search

Calendar

<<  September 2014  >>
SuMoTuWeThFrSa
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

Sign in

Twitter


    follow OffBeatMammal at http://twitter.com


    Amazon Store


     
    Donate unused CPU cycles with BOINC Stats and Account Management from BOINCStats.com



    Blogroll

    Archive

    Tags

    Categories


    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2014