JavaScript comma counter
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate (form) {
var TestVar = form.inputbox.value;
myArray = TestVar.split(',');
document.write(myArray.length);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE="" OnBlur="validate(this.form)" onkeydown="validate(this.form)" onkeyup="validate(this.form)" ><P>
<script type="text/javascript">validate(this.form);</script>
</FORM>
</BODY>
</HTML>
Can someone please help me fix this. As soon as I press a key down, it ends. I want it to update inde开发者_StackOverflow社区finitely.
Example:
input: hello
output: 1 input hello, good, bye output: 3 ...
When you do document.write()
after your document has been loaded, it clears your current document and starts writing a new one. Don't use document.write()
after your document has been loaded except in rare cases where that's the effect you want. That is not what you want here.
If you're just trying to see what the myArray.length value is for debugging purposes, then use console.log()
instead of document.write()
and look at it in the console/debug window.
Even better would be to use one of the javascript debuggers (Firebug for Firefox or the built-in debugger in Chrome, Opera and Safari) and set a breakpoint in your validate function and just inspect the variable as it happens.
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
</HEAD>
<BODY>
<form name="myForm">
<input type="text" id="inputbox" onkeydown="validate(form.this)"/>
<input type="text" name="textf"/>
</FORM>
<SCRIPT LANGUAGE="JavaScript">
function validate () {
var TestVar = myForm.inputbox.value;
var myArray = TestVar.split(',');
document.myForm.textf.value = myArray.length;
}
</SCRIPT>
</BODY>
</HTML>
That was easy.
精彩评论