Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Character count minus spaces

Status
Not open for further replies.

floofy7

Programmer
Jul 24, 2006
11
US
I need this character count to NOT include spaces typed in each of the 4 fields.

Can you help?

Thanks! :)

MY CODE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<html xmlns="<head>
<title>Untitled Document</title>
<script type="text/javascript">
function countChars()
{
document.form1.count_display.value = (document.form1.text_1.value.length + document.form1.text_2.value.length + document.form1.text_3.value.length + document.form1.text_4.value.length);
}

</script>
</head>
<body>
<form action="" name="form1" id="form1">
<p><input name="text_1" onkeyup="countChars();" onblur="countChars();" /></p>
<p><input name="text_2" onkeyup="countChars();" onblur="countChars();" /></p>
<p><input name="text_3" onkeyup="countChars();" onblur="countChars();" /></p>
<p><input name="text_4" onkeyup="countChars();" onblur="countChars();" /></p>
<br />
<p>Char Count: <input type="text" name="count_display" value="0" size="4" readonly="readonly" /></p>
</form>
</body>
</html>
 
You can try it using a replace method:
Code:
...
var frm = document.form1;
frm.count_display.value = frm.text_1.value.replace(" ","").length + frm.text_2.value.replace(" ","").length + frm.text_3.value.replace(" ","").length + frm.text_4.value.replace(" ","").length;
...
The code is hardly optimised, but it ought to show how you can use replace to replace all spaces (" ") with an empty string ("").

Cheers,
Jeff

[tt]Visit my blog [!]@[/!] Visit Code Couch [!]@[/!] [/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
[tt]function countChars()
{
var rx=/\w/g;
var s="";
var n=0;
with (document.form1) {
for (var i=1;i<5;i++) {
s+=elements["text_"+i].value;
}
if (rx.test(s)) {
n=s.match(rx).length;
}
count_display.value=n;
}
}[/tt]
 
In case the above filtered too many, you can use an expression strictly excluding blankspace nothing else.
[tt]
[red]//[/red]var rx=/\w/g;
var rx=/[^ ]/g;
[/tt]
But one can image whole spectrum of filter between the two limits.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top