For example, once the user types 101 characters, I'd like to pop up an
alert that says "You have typed more than the maximum allowed!"
How can I do this?
TIA
Matt
You need to attach a function to the input elements onkeyup event, like this:
function validate_input(event) {
if(event.target().value.length > 100) {
alert("you typed more than 100 characters");
}
}
MochiKit.Signal.connect(my_form.elements['elementname'], 'onkeyup',
validate_input);
But you are aware that the html input controls have a limit property
themselves, called "maxlength".
Diez
Yes, but textarea elements don't seem to have such an attribute:
http://www.w3.org/TR/html401/interact/forms.html#h-17.7
If you need this, instead of popping up an annoying alert box, you could
set a visible counter on each keyup instead, that shows how many
characters are left and suppress further input if it exceeds the limit:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Counter test</title>
<script type="text/javascript" src="MochiKit.js"></script>
<script type="text/javascript">
var maxlength=100;
function count_input(e) {
if (e)
var text = e.src();
else
var text = $('text');
var chars_left = maxlength - text.value.length;
if (chars_left >= 0)
$('counter').value = chars_left;
else if (e) {
text.value = text.value.slice(0, maxlength);
e.stop();
}
}
connect(window, 'onload',
function() {
connect($('text'), 'onkeyup', count_input);
count_input();
}
);
</script>
</head>
<body>
<textarea id="text" cols="30" rows="4"></textarea><br />
Chars left: <input type="text" id="counter" size="4" readonly />
</body>
</html>
HTH, Chris