Need help with textboxes

K

Kodiak

I am trying to write some javascript code in which you enter some text
in one text box and the text will also appear in the second text box.
For example, if I write the word "Test" both text boxes should have
the same word in them. I need to be able to see the work actually
being typed out in both text boxes as well. If I trye the letter T
then both text boxes should have the same result all the type. If I
delete the letter T then both boxes should delete the letter T and so
forth. If anyone can help with this problem I woule really appreciate
it. Here is a code sample I am using below!

<html>
<head>
<script type="text/javascript">
function checkKey()
{
txtOutput.value = txtEnterValue.value;
}
</script>
</head>

<body>

<p>Type a word.<br>
<input type="text" name="txtEnterValue" onkeypress="checkKey()"> </
p>
<p>The result should appear in this box as you type.<br>
<input type="text" name="txtOutput"> </p>

</body>
</html>
 
D

Daz

I am trying to write some javascript code in which you enter some text
in one text box and the text will also appear in the second text box.
For example, if I write the word "Test" both text boxes should have
the same word in them. I need to be able to see the work actually
being typed out in both text boxes as well. If I trye the letter T
then both text boxes should have the same result all the type. If I
delete the letter T then both boxes should delete the letter T and so
forth. If anyone can help with this problem I woule really appreciate
it. Here is a code sample I am using below!

<html>
<head>
<script type="text/javascript">
function checkKey()
{
txtOutput.value = txtEnterValue.value;}

</script>
</head>

<body>

<p>Type a word.<br>
<input type="text" name="txtEnterValue" onkeypress="checkKey()"> </
p>
<p>The result should appear in this box as you type.<br>
<input type="text" name="txtOutput"> </p>

</body>
</html>

Neither txtEnterValue or txtOutput are variables in the global scope.

I would suggest putting your text inputs inside of a form where they
belong, then modifying the onkeypress event to pass back a reference
to the form, like so...

<html>
<head>
<script type="text/javascript">
function checkKey(form)
{
form.txtOutput.value = form.txtEnterValue.value;
}

</script>
</head>

<body>
<form name="myForm">
<p>
Type a word.<br>
<input type="text" name="txtEnterValue"
onkeypress="checkKey(this.form)">
</p>
<p>
The result should appear in this box as you type.<br>
<input type="text" name="txtOutput">
</p>
</form>
</body>
</html>

You'll find that you get some strange behaviour, however, as the event
fires the moment it's pressed, which is before it actually types a
character into the input box. I would recommend using "onkeyup"
instead. If it's important to you that the characters appear almost
instantaneously, you can use a timer. This means that just about each
character should appear as it's entered if the timer function executes
often enough, and will compensate for when a user holds down a key.

<html>
<head>
<script type="text/javascript">
function copyText() {
document.forms['myForm'].txtOutput.value =
document.forms['myForm'].txtEnterValue.value
}

window.onload = function() {
setInterval("copyText()", 50)
}
</script>
</head>

<body>
<form name="myForm">
<p>
Type a word.<br>
<input type="text" name="txtEnterValue">
</p>
<p>
The result should appear in this box as you type.<br>
<input type="text" name="txtOutput">
</p>
</form>
</body>
</html>

Note that here, I've used a different method to get the information
from the form. All forms and their children are stored in an array
called "forms", which is a property of the "document". So, to access
children in a form with the name "anotherForm", you could do this:

document.forms.anotherForm.elementName

You can also access it like this:

document["forms"]["anotherForm"]["someChildName"]

Although it should only be used if needed, as dot notation is better
and more consistent, and looks neater.

What you see above, is basically a multi dimensional array.

You can also call on a form by it's position in the document array:

document.form[0]

Personally, I don't do this, as I believe it leaves more to go wrong.


My examples are from from perfect. They simply show a few fundamental
techniques for achieving what you want (and there or many more). There
is no reason why you couldn't use a combination of "onkeydown", and
"onkeyup" along with the timer. The timer can be activated when the
key goes down, and deactivated when the key goes up.

Hope this helps.
 
L

Lee

Kodiak said:
I am trying to write some javascript code in which you enter some text
in one text box and the text will also appear in the second text box.
For example, if I write the word "Test" both text boxes should have
the same word in them. I need to be able to see the work actually
being typed out in both text boxes as well.

That's a pretty silly requirement. Is this for a class?


--
 
D

Daz

That's a pretty silly requirement. Is this for a class?

--

Sorry Lee, but that's a pretty arrogant statement...

The fact that the OP is having trouble obtaining references to form
elements, strongly suggests that he's just starting out with
JavaScript. That doesn't mean he has to write something useful to
start with. I am sure his only goal is to create something simple, and
understand how it works, even if it serves no real purpose.

While criticism is usually welcome, it's usually only welcome when
it's helpful, and reasons as to why a particular method of doing
something may not be the best. You're comment offers absolutely no
help, and gives the impression that anything posted will put under
scrutiny, which is not what we are here to do.
 
T

Thomas 'PointedEars' Lahn

Daz said:
You'll find that you get some strange behaviour, however, as the event
fires the moment it's pressed, which is before it actually types a
character into the input box. I would recommend using "onkeyup"
instead.

That part is actually the only good advice in your posting.
If it's important to you that the characters appear almost
instantaneously, you can use a timer. This means that just about each
character should appear as it's entered if the timer function executes
often enough, and will compensate for when a user holds down a key.

It will not, that is bad advice. ECMAScript implemenations are
single-threaded, and system timer tick intervals may be higher
than the 50 ms alotted here.

It is also not necessary to use a timer function for "instantaneous"
appearance. Listening to mouse and keyboard events suffices.

A DOCTYPE declaration is missing before.

A declaration of the used encoding and the default scripting language is
missing here.
<script type="text/javascript">
function copyText() {
document.forms['myForm'].txtOutput.value =
document.forms['myForm'].txtEnterValue.value
}

Yuck. This can be improved in a number of ways, including the most simple
one of assigning the reference to a variable:

var f = document.forms['myForm'], es = f.elements;

And then:

es["txtOutput"].value = es["txtEnterValue"].value;
window.onload = function() {

This is a proprietary definition of an event listener, inherently
error-prone. It is not necessary, as the HTML `body' element has
an intrinsic standards-compliant `onload' event handler attribute
to facilitate this.
setInterval("copyText()", 50)

Because of the unknown timer tick interval, it is better to use
setTimeout() instead of setInterval() for time-critical processes.

Both methods are proprietary properties of Window host objects and
should be called so: window.setTimeout(...), window.setInterval(...)
}
</script>
</head>

<body>

<body onload="...">

See above.
<form name="myForm">

The `action' attribute is required. The `name' attribute would be
unnecessary if you simply passed the element reference "onkeyup" with
`this.form' or `this' (the latter being most compatible).
<p>
Type a word.<br>
<input type="text" name="txtEnterValue">

`type="text"' is redundant as that is the default value.

<input name="txtEnterValue"
onkeyup="copyText(this.form)">

Nonsense. The `p' element is to mark up *p*aragraphs. There is no
paragraph here, so the `div' element should be used instead.
<p>
The result should appear in this box as you type.<br>
<input type="text" name="txtOutput">

See above.
</p>
</form>
</body>
</html>

Your markup is far from being syntactically or semantically correct.
Due to the former, it is unlikely to work consistently:
http://diveintomark.org/archives/2003/05/05/why_we_wont_help_you

For syntactical correctness, consult at least http://validator.w3.org/
Note that here, I've used a different method to get the information
from the form. All forms and their children are stored in an array
called "forms",

`forms' is not an array, see below. `children' is too limited, because
a reference to a HTMLFormElement includes access to all its descendant elements.
which is a property of the "document". So, to access children in a form
with the name "anotherForm", you could do this:

That is not accessing `children' of/in the form, it is accessing form
controls represented by DOM objects, which is quite different. `children'
would include all child elements. Neither need form controls be child
elements of the `form' element, nor can a form contain only form controls.
document.forms.anotherForm.elementName

This is completely proprietary referencing, and so inherently error-prone.
Mostly standards-compliant and fully backwards-compatible referencing of the
above would be

document.forms["anotherForm"].elements["elementName"]
You can also access it like this:

document["forms"]["anotherForm"]["someChildName"]

That is not standards-compliant either.

document["forms"]["anotherForm"]["elements"]["someChildName"]

would be.
Although it should only be used if needed, as dot notation is better

It would only be better if standards-compliant referencing was used.
and more consistent,

No. Bracket property accessors allow their argument to be any string value.
Dot property accessors require their operand to be an identifier. Using
dot property accessors in favor of bracket property accessors will cause a
mix of dot and bracket property accessors in cases where the control name is
not an identifier. This is explained in the FAQ.

However, W3C DOM Level 2 HTML specifies that referencing the items of a
HTMLCollection object in an ECMAScript implementation is (only) supported
through the bracket property accessor, so there is not much choice here:

http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html
(see the description for the namedItem() method of HTMLCollection objects)
and looks neater.

Only a matter of opinion.
What you see above, is basically a multi dimensional array.

Not at all. It is merely a sequence of property accesses, where the first
property access is resolved first, then the second, and so forth.

ECMAScript implementations have no built-in concept of associative arrays,
i.e. arrays where the index may also be a non-numeric string. If such
referencing is used on Array objects, that is not adding elements to the
array data structure, but adding properties to the Array object which
encapsulates that data structure. As indicated by the Array object's
length property to yield an unchanged value.
You can also call on a form by it's position in the document array:

Neither `document' nor `document.forms' are arrays. `document' is a
reference to an HTMLDocument object, and `document.forms' is therefore
a reference to an HTMLCollection object.

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268
document.form[0] [...]
My examples are from from perfect.

Your misconceptions about the used languages and interfaces are numerous.
You should refrain from giving further advice until you have grasped the
basics of that, because any advice you might give in spite of that has a
very high probability of being bad advice. That would force more
knowledgeable people to correct most if not all of your postings and to
waste their time with that, in place of or in addition to investing time
to post good advice.


PointedEars
 
E

Evertjan.

Daz wrote on 16 sep 2007 in comp.lang.javascript:

[please do not quote even part of a signature on usenet]
Sorry Lee, but that's a pretty arrogant statement...

The fact that the OP is having trouble obtaining references to form
elements, strongly suggests that he's just starting out with
JavaScript. That doesn't mean he has to write something useful to
start with. I am sure his only goal is to create something simple, and
understand how it works, even if it serves no real purpose.

While criticism is usually welcome, it's usually only welcome when
it's helpful, and reasons as to why a particular method of doing
something may not be the best. You're comment offers absolutely no
help, and gives the impression that anything posted will put under
scrutiny, which is not what we are here to do.

So there exists a "what we are here to do"?

That certainly must be your personal conception of usenet,
that it is one gigantic helpdesk.

Iteration:
... a pretty arrogant statement

I certainly don't think it is arrogant,
and I would not use those words easily if I where you,
but I deduct I am not.

Reiteration:
I too would like an answer to that from the OP.

While the requirement is rather silly,
it is a good subject for a home experiment in a teaching assignment.

If so, we should, I think not spoil the learning effect by doing such
experiment for him or her.
 
L

Lee

Daz said:
Sorry Lee, but that's a pretty arrogant statement...

Pot. Kettle.
The fact that the OP is having trouble obtaining references to form
elements, strongly suggests that he's just starting out with
JavaScript. That doesn't mean he has to write something useful to
start with. I am sure his only goal is to create something simple, and
understand how it works, even if it serves no real purpose.

While criticism is usually welcome, it's usually only welcome when
it's helpful, and reasons as to why a particular method of doing
something may not be the best. You're comment offers absolutely no
help, and gives the impression that anything posted will put under
scrutiny, which is not what we are here to do.

Certainly it is part of "what we are here to do". If you blindly
give every poster exactly what they ask for, without considering
why they're asking for it, and what misconceptions or ulterior
motives may lie beneath the request, you're being irresponsible.

Years of experience in this newsgroup suggests that when a poster
asks for something that's trivial and pointless, there's a very
good chance that it's a homework assignment. We shouldn't be
doing homework assignments for students. Do you disagree?

You'll notice that I didn't refuse help. They had already
received help. I simply pointed out why I suspected that it
may be a homework assignment and asked if it, in fact, is.

It may well not be. It might be an attempt at learning on their
own, in which case, more power to them, or it might be an ill-
conceived required "feature" on a web site. There might even be
a very good reason for it, but the odds seem to be against it.

It certainly seems worth asking.


--
 
R

RobG

I too would like an answer to that from the OP.

While the requirement is rather silly,
it is a good subject for a home experiment in a teaching assignment.

If so, we should, I think not spoil the learning effect by doing such
experiment for him or her.

That presumes that the "learning effect" of struggling with a problem
is more useful that being taught the answer.

Giving novice students brain teasers and expecting them to work it out
themselves is not always the best way to teach. Recent experiments
show that for new learning, it is much more valuable to present
questions with fully worked examples and solutions. Questions that
require application of knowledge should only be asked once the basic
knowledge has been acquired.

Whether the question originated from a school assignment or someone
trying to learn from some other source doesn't make much difference to
me. Such a basic question infers a very new student, the answer
should be framed within that context.
 
E

Evertjan.

RobG wrote on 17 sep 2007 in comp.lang.javascript:
That presumes that the "learning effect" of struggling with a problem
is more useful that being taught the answer.

Indeed it does.
Giving novice students brain teasers and expecting them to work it out
themselves is not always the best way to teach.

I wouldn't think that is a good way to go, not without asking the OP what
it's intentions are, and what work he/dhe has done sofar.
Recent experiments
show that for new learning, it is much more valuable to present
questions with fully worked examples and solutions. Questions that
require application of knowledge should only be asked once the basic
knowledge has been acquired.

I wouln't trust those "recent experiments", since they are
counterintuitive and I don't know what controlled environment is
presumed.
Whether the question originated from a school assignment or someone
trying to learn from some other source doesn't make much difference to
me. Such a basic question infers a very new student, the answer
should be framed within that context.

So, as I said, without confirmation of tat context, we should presume the
OP is helped best by not answering his/her school asignment for him/her.
 
D

Daz

That part is actually the only good advice in your posting.

Ouch... My purpose was to give an example that could be seen working,
not do do it for him. He wanted to know how to achieve, and I did that
in my example. It's not meant to be code that can be copied and handed
in as school work (if that's what it's for).
It will not, that is bad advice. ECMAScript implemenations are
single-threaded, and system timer tick intervals may be higher
than the 50 ms alotted here.

It is also not necessary to use a timer function for "instantaneous"
appearance. Listening to mouse and keyboard events suffices.

Are you talking about recursion? I'd be interested to see your
implementation.
A DOCTYPE declaration is missing before.


A declaration of the used encoding and the default scripting language is
missing here.
I know. Firstly, this is a JavaScript UseNet group, not HTML. Also, as
I mentioned before, it was a quick example that shows a possible
method of doing it. The aim was to inspire, not to do it for the OP.
<script type="text/javascript">
function copyText() {
document.forms['myForm'].txtOutput.value =
document.forms['myForm'].txtEnterValue.value
}

Yuck. This can be improved in a number of ways, including the most simple
one of assigning the reference to a variable:

var f = document.forms['myForm'], es = f.elements;

And then:

es["txtOutput"].value = es["txtEnterValue"].value;
window.onload = function() {

The example was meant to be clear. I didn't say it was the best way,
nor did I state the code was optimized for speed. In fact, I
specifically said that my example was "far from perfect". "Far"
implies a long way. There's always room for improvement.
This is a proprietary definition of an event listener, inherently
error-prone. It is not necessary, as the HTML `body' element has
an intrinsic standards-compliant `onload' event handler attribute
to facilitate this.


Because of the unknown timer tick interval, it is better to use
setTimeout() instead of setInterval() for time-critical processes.

That, I didn't know. What does setInterval() use then, if it's not
system ticks? I was always under the impression that they were built
on the same foundations, but just worked differently.
Both methods are proprietary properties of Window host objects and
should be called so: window.setTimeout(...), window.setInterval(...)

I know this, although I don't see much of a point... I suppose you
write all of your global variable and functions like that too?
<body onload="...">

See above.


The `action' attribute is required. The `name' attribute would be
unnecessary if you simply passed the element reference "onkeyup" with
`this.form' or `this' (the latter being most compatible).

I know, but again, it was a quick example to outline a possible
solution, not to demonstrate perfect HTML. I don't recall the OP
asking about how to write perfect HTML (let me draw your mind back to
the bit where I said "My code is far from perfect").
`type="text"' is redundant as that is the default value.

<input name="txtEnterValue"
onkeyup="copyText(this.form)">


Nonsense. The `p' element is to mark up *p*aragraphs. There is no
paragraph here, so the `div' element should be used instead.

That was the OP's code, and if that's what he wanted to do, that's
down to him. What's wrong with just answering a question rather than
answering a whole heap of questions he didn't even ask?
See above.


Your markup is far from being syntactically or semantically correct.
Due to the former, it is unlikely to work consistently:http://diveintomark.org/archives/2003/05/05/why_we_wont_help_you
Validation may reveal your problem - It wouldn't. The problem was with
the method (not even the JavaScript itself...

Validation may solve your problem - Again, it wouldn't.

Valid markup is hard enough to debug already - Agreed, but I didn't
ask you for help with bad markup from me. In fact, I didn't even debug
as such. I just offered a solution. I thought this group was aimed at
JavaScript, not HTML. It was hardly a massive script, and if you
didn't want to help, I have no problem with that. I was in the
position to help, so I did.

Validation is an indicator of cluefulness - I couldn't agree more, but
we are talking about HTML validation for a JavaScript problem, when
you know as well as I do that wasn't the problem. Also, it's pretty
obvious that the OP isn't experienced.
For syntactical correctness, consult at leasthttp://validator.w3.org/
I do... Plus HTML Tidy is an integral part of my development kit...
`forms' is not an array, see below. `children' is too limited, because
a reference to a HTMLFormElement includes access to all its descendant elements.

That was my bad. I meant to actually say "object". That's exactly what
it is, but it does "act" like a multi-dimensional array.
That is not accessing `children' of/in the form, it is accessing form
controls represented by DOM objects, which is quite different. `children'
would include all child elements. Neither need form controls be child
elements of the `form' element, nor can a form contain only form controls.

I agree with you there. It is limited, but I was trying to keep it
simple.
document.forms.anotherForm.elementName

This is completely proprietary referencing, and so inherently error-prone.
Mostly standards-compliant and fully backwards-compatible referencing of the
above would be

document.forms["anotherForm"].elements["elementName"]
You can also access it like this:
document["forms"]["anotherForm"]["someChildName"]

That is not standards-compliant either.

document["forms"]["anotherForm"]["elements"]["someChildName"]

would be.

Please could you post a link to the documentation that states this? I
have to admit, I did go through a time when I didn't know whether to
use dot notation or object literals. Generally, I use dot notation
unless I need to call on a dynamically generated property.

I use jslint.com to validate my HTML.

I put both of our lines of script into a variable, and checked it with
JSLint.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]
Error:

Implied global: document

Problem at line 1 character 19: ['forms'] is better written in dot
notation.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]

Problem at line 1 character 28: ['anotherForm'] is better written in
dot notation.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]

Problem at line 1 character 43: ['elements'] is better written in dot
notation.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]

Problem at line 1 character 55: ['someChildName'] is better written in
dot notation.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]

Problem at line 1 character 71: Missing semicolon.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]

------------------------

var el = document.forms.anotherForm.elements.someChildName;

Error:

Implied global: document

OK, so I got one error, and perhaps should have prefix "document" with
"window".

If you think my single line of code is wrong, perhaps you should take
it up with Douglas Crockford? I don't mean that in a horrible way, I'd
just be interested to see what he says.

Again, I didn't say my methods were correct, I simply stated that it
was another way of doing it.
It would only be better if standards-compliant referencing was used.


No. Bracket property accessors allow their argument to be any string value.
Dot property accessors require their operand to be an identifier. Using
dot property accessors in favor of bracket property accessors will cause a
mix of dot and bracket property accessors in cases where the control name is
not an identifier. This is explained in the FAQ.

However, W3C DOM Level 2 HTML specifies that referencing the items of a
HTMLCollection object in an ECMAScript implementation is (only) supported
through the bracket property accessor, so there is not much choice here:

You mean "dereferencing"?
http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html
(see the description for the namedItem() method of HTMLCollection objects)


Only a matter of opinion.


Not at all. It is merely a sequence of property accesses, where the first
property access is resolved first, then the second, and so forth.

Then we'll have to agree to disagree. Perhaps it's just me, but it
sounds like you just "described" a multi-dimensional array. I didn't
say it "was" a multi-dimensional array, I simply compared it to one.

Here's a multi-dimensional array:
var arr = [];
arr["first_property"] = 1;
arr["second_property"] = 2;
arr["third_property"] = [];
arr["third_property"]["first_property"] = 4;
arr["third_property"]["second_property"] = function() { alert(5); };
arr["third_property"]["third_property"] = 6;

alert(arr.second_property);
arr.third_property.second_property();

Here's the equivilant object:

var obj = {}
obj.first_property = 1;
obj.second_property = 2;
obj.third_property = {}
obj.third_property.first_property = 4;
obj.third_property.second_property = function() { alert(5) };
obj.third_property.third_property = 6;

alert(obj.second_property);
obj.third_property.second_property();

They are different methods of "Basically" achieving the same thing.
Array() is based on an object (as is everything else), the only
fundamental differences are the properties and methods.

Please don't start ranting about recommendations and standards. I am
well aware that it's not standard, but it should illustrate that when
I compared an object is basically a multi-dimensional array, that
there is truth in that. Again, I didn't say "it was", I simply
compared them.
ECMAScript implementations have no built-in concept of associative arrays,
i.e. arrays where the index may also be a non-numeric string. If such
referencing is used on Array objects, that is not adding elements to the
array data structure, but adding properties to the Array object which
encapsulates that data structure. As indicated by the Array object's
length property to yield an unchanged value.


Neither `document' nor `document.forms' are arrays. `document' is a
reference to an HTMLDocument object, and `document.forms' is therefore
a reference to an HTMLCollection object.

I didn't say it was...
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268


document.form[0] [...]
My examples are from from perfect.

Your misconceptions about the used languages and interfaces are numerous.
You should refrain from giving further advice until you have grasped the
basics of that, because any advice you might give in spite of that has a
very high probability of being bad advice. That would force more
knowledgeable people to correct most if not all of your postings and to
waste their time with that, in place of or in addition to investing time
to post good advice.

So in your effort to "not do someone's homework for them", you've
actually gone and done it for them.
PointedEars

Haha, nice signature!
 
D

Daz

Daz said:





Pot. Kettle.



Certainly it is part of "what we are here to do". If you blindly
give every poster exactly what they ask for, without considering
why they're asking for it, and what misconceptions or ulterior
motives may lie beneath the request, you're being irresponsible.

Years of experience in this newsgroup suggests that when a poster
asks for something that's trivial and pointless, there's a very
good chance that it's a homework assignment. We shouldn't be
doing homework assignments for students. Do you disagree?

You'll notice that I didn't refuse help. They had already
received help. I simply pointed out why I suspected that it
may be a homework assignment and asked if it, in fact, is.

It may well not be. It might be an attempt at learning on their
own, in which case, more power to them, or it might be an ill-
conceived required "feature" on a web site. There might even be
a very good reason for it, but the odds seem to be against it.

It certainly seems worth asking.

--

I apologise, and take back my statement. It seemed to me as though you
were saying that what he was wanting to do was "pretty silly".

When you mentioned a class, I thought you were referring to a
JavaScript class (object), it never occured to me that you meant
educational class. Hopefully you can see where I was coming from,
taking your post in the context that I did. I've seen many posts which
set out (or at least appear to set out), to flame someone, and their
ideas.

My humble apologies again. Now if you'll excuse me, I have a rather
large foot to remove from my mouth.
 
T

Thomas 'PointedEars' Lahn

Daz said:
Ouch... My purpose was to give an example that could be seen working,
not do do it for him. He wanted to know how to achieve, and I did that
in my example. It's not meant to be code that can be copied and handed
in as school work (if that's what it's for).

Still, would you agree that wrong examples serve little practical purpose?
Are you talking about recursion?

Hardly. What would recursion have to do with the above?
I'd be interested to see your implementation.

Why, the "implementation" is listen to mouse and keyboard events,
particularly mousedown, mouseup, click, keyup, keydown, and keypress.
That, I didn't know. What does setInterval() use then, if it's not
system ticks?

It does use system timer ticks which is the cause of the problem with it
when it comes to time-critical applications.
I was always under the impression that they were built
on the same foundations, but just worked differently.

I read an interesting and IMHO sound argument about setInterval() vs.
setTimeout() in another thread here not long ago, but I don't have the
reference anymore. IIRC, it goes like this:

ECMAScript implementations are single-threaded. window.setInterval()
*attempts* to execute code every n milliseconds despite of that. Consider
that at that time another process/thread has priority, there are two
possibilities: either the application will execute the interval code
at the next available tick, or it will execute it at the next planned
opportunity, n milliseconds after the tick that could not be used.
Either way, the supposed calls are likely to accumulate here.

With setTimeout(), the application will have no choice but to execute it
at the next available tick; and only then the new timeout will be set.
So nothing can accumulate then.
I know this, although I don't see much of a point...

Not calling them as methods of Window objects assumes that the Global Object
or an unknown host object in the scope chain has such host-defined
properties. This would be error-prone.
I suppose you write all of your global variable and functions like
that too?

Of course not. Those are properties of the Global Object, not of a host
object that may or may not be available as such and may or may not share
the Global Object's properties. If I would do what you assume, that would
be error-prone, too.

The JavaScript 1.5 Reference already states:

,-<http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects
|
| The [G]lobal [O]bject itself can be accessed by `this' in the global
| scope.

And rightly so; that is specified in ECMA-262 since its very first edition.
That was the OP's code, and if that's what he wanted to do, that's
down to him. What's wrong with just answering a question rather than
answering a whole heap of questions he didn't even ask?

If you had the intention to give him a hint as how to solve his problem, it
would have been a Good Thing to post a reasonable example, even though the
original code was bad. That would not have involved "answering a whole head
of questions": a short note as to why it is bad along with the improved code
would have sufficed.

That this newsgroup is not a newsgroup dealing primarily with HTML is a
null argument; we are attempting to write good code here, no matter the
language. In fact, it turns out that bad HTML, CSS etc. code often is
the cause of a script written in an ECMAScript implementation not to
function. You simply can't build a house on quicksand.
Validation may reveal your problem - It wouldn't. The problem was with
the method (not even the JavaScript itself...

Validation may solve your problem - Again, it wouldn't.

You can not know that.
[...]
Validation is an indicator of cluefulness - I couldn't agree more, but
we are talking about HTML validation for a JavaScript problem, when
you know as well as I do that wasn't the problem. Also, it's pretty
obvious that the OP isn't experienced.

So the logical course of action would be to deny them access to further
knowledge?
That was my bad. I meant to actually say "object". That's exactly what
it is, but it does "act" like a multi-dimensional array.

It does not.
document.forms.anotherForm.elementName
This is completely proprietary referencing, and so inherently error-prone.
Mostly standards-compliant and fully backwards-compatible referencing of the
above would be

document.forms["anotherForm"].elements["elementName"]
You can also access it like this:
document["forms"]["anotherForm"]["someChildName"]
That is not standards-compliant either.

document["forms"]["anotherForm"]["elements"]["someChildName"]

would be.

Please could you post a link to the documentation that states this?

I did.
I have to admit, I did go through a time when I didn't know whether to
use dot notation or object literals. Generally, I use dot notation
unless I need to call on a dynamically generated property.

I use jslint.com to validate my HTML.

I put both of our lines of script into a variable, and checked it with
JSLint.

var el = document["forms"]["anotherForm"]["elements"]["someChildName"]
Error:

Implied global: document

Problem at line 1 character 19: ['forms'] is better written in dot
notation.

The statement is correct. That should have been only a warning, though.
var el = document["forms"]["anotherForm"]["elements"]["someChildName"]

Problem at line 1 character 28: ['anotherForm'] is better written in
dot notation.

That is incorrect, as I have pointed out and referred to reference material.
If you think my single line of code is wrong, perhaps you should take
it up with Douglas Crockford? I don't mean that in a horrible way, I'd
just be interested to see what he says.

jslint is a tool to check for possible errors and bad code style. It does
not recognize the context of a script. That is not really a flaw of it, but
something that has to be considered by people who use it.

As Douglas Crockford is a regular here, I am pretty sure he will comment on
that eventually.
Again, I didn't say my methods were correct, I simply stated that it
was another way of doing it.

Proposing bad style is a Bad Thing, period.

As I wrote, you could simply have refrained from replying to the OP.
A more knowledgable person than you would most certainly have replied
with a much better S/N ratio.
You mean "dereferencing"?

That would imply ECMAScript implementations have a concept of pointers,
which they have not.
Then we'll have to agree to disagree. Perhaps it's just me,

No, it is a common misconception about the language, last but not least
transported or induced into the mind of beginners by bad books.
but it sounds like you just "described" a multi-dimensional array. I didn't
say it "was" a multi-dimensional array, I simply compared it to one.

Here's a multi-dimensional array:

There isn't. I have explained already why, mentioning exactly the below
example. But as you insist:
var arr = [];

That is creating a new Array object and assigning the reference to it
to the previously instantiated variable `arr'.

I will assume in the following for brevity that `arr' is a global variable.
arr["first_property"] = 1;

That is adding the `first_property' property with value 1 to the Array object.

arr.length remains 0. arr.join("") yields "", not "1".
arr["second_property"] = 2;

That is adding the `second_property' property with value 2 to the Array object.

arr.length remains 0. arr.join("") yields "", not "12".
arr["third_property"] = [];

That is adding the `third_property' property with a reference to a new Array
object to the Array object referenced with `arr'

arr.length remains 0. arr.join("") yields "", not "12".
arr["third_property"]["first_property"] = 4;

That is adding the `first_property' property with the value 0 as property of
the array object referenced by arr["third_property"].

Both arr.length and arr["third_property"].length remain 0. arr.join("")
yields "", not "124". arr["third_property"].join("") yields "", not "4".
arr["third_property"]["second_property"] = function() { alert(5); };

That is adding the `second_property' property with a reference to a new
Function object as property of the Array object referenced by
arr["third_property"].

Both arr.length and arr["third_property"].length remain 0. arr.join("")
yields "", not "124,function() { alert(5); }".
arr["third_property"].join("") yields "", not "4function() { alert(5); }".
arr["third_property"]["third_property"] = 6;

That is adding the `third_property' property with a reference to a new
Function object as property of the array object referenced by
arr["third_property"].

Both arr.length and arr["third_property"].length remain 0. arr.join("")
yields "", not "124,function() { alert(5); },6".
arr["third_property"].join("") yields "", not "4function() { alert(5); }6".
alert(arr.second_property);

That is calling the alert() method (of Window objects, error-prone called as
a method of the Global Object or another object in the scope chain). It is
passed the evaluation of the dot property access to the `arr' property of
the Global Object, which yields an (Array) object; that object has a
`second_property' property which is of type number; the value is converted
to string with ToString(), and (maybe) displayed.
arr.third_property.second_property();

That is evaluated as follows: `arr' is determined a property of the Global
Object, which yields an (Array) object; that object has a `third_property'
property which yields an (Array) object; that object has a second_property
property which is of type Function; the grammar dictates that because of
the (empty) parameter list and the absence of the `new' keyword, that
Function object must [[Call]]ed, which is then done.
Here's the equivilant object:

The only equivalence here is that all objects may have properties, and that
native objects, such as Object objects and Array objects, may be added
(user-defined) properties.
var obj = {}

This is creating a new Object object, and assigning a reference to the
previously instantiated variable `obj'. That object inherits only from
Object.prototype; not from Array.prototype as the object referenced with
`arr' does.
obj.first_property = 1;

I won't repeat the above. Suffice it to say that

obj["first_property"] = 1;

is (of course) equivalent. The difference is only the property accessor
syntax used.
obj.second_property = 2;

obj["second_property"] = 2;
obj.third_property = {}

obj["third_property"] = {};
obj.third_property.first_property = 4;

obj["third_property"].first_property = 4;

or

obj["third_property"]["first_property"] = 4;
obj.third_property.second_property = function() { alert(5) };

obj["third_property"].second_property = function() { alert(5) };

or

obj["third_property"]["second_property"] = function() { alert(5) };
obj.third_property.third_property = 6;

obj["third_property"].third_property = 6;

or

obj["third_property"]["third_property"] = 6;
alert(obj.second_property);

alert(obj["second_property"]);

or (better)

window.alert(obj["second_property"]);
obj.third_property.second_property();
obj["third_property"].second_property();

or

obj["third_property"]["second_property"]();

They are different methods of "Basically" achieving the same thing.

That much is true.
Array() is based on an object (as is everything else), the only
fundamental differences are the properties and methods.

There is much more to Array objects (see ECMA-262 Ed. 3), if array
properties are used.

As they are not used here, the fundamental difference is that the Array
object wastes more memory, and inherits more properties and methods from
its prototype object (which inherits from Object.prototype) that are not
used but can interfere.

So an Object object, which inherits only from Object.prototype, should
have been used in the first place (no matter the property access syntax used).
Please don't start ranting about recommendations and standards.

Mentioning recommendations and standards is only ranting for those who fail
to recognize their utmost significance when it comes to interoperability.
I am well aware that it's not standard,

You are not aware that the language specification explicitly allows that
approach for *native* objects. Which does not mean in any way that it would
be wise to (mis)use Array objects like this.

However, DOM interfaces are a completely different thing. The standard for
*that*, W3C DOM Level 2 HTML, states that bracket property accessors must be
used for referencing items of HTMLCollection objects. It is specified so,
period.
but it should illustrate that when I compared an object is basically a
multi-dimensional array, that there is truth in that.

Not in the least.
Again, I didn't say "it was", I simply compared them.

Your comparison was based on a (common) misconception.
I didn't say it was...

But your statement at least implied this. Don't try to wind around that.

(sic!)

You have destroyed the context.
So in your effort to "not do someone's homework for them", you've
actually gone and done it for them.

You are confused. I have never stated that I would "not do someone's
homework for them" (although I would probably not do that without proper
compensation in any form). However, you made it necessary to correct your
wrong example and false statements (or implications, if you wish). If not
only you but also others, including the OP, can learn from that, so be it.

Still, the unlearning that is now required by them (again; if they even
recognized or understood the correction(s) which ended up being quite large
because of the sheer number of errors) would not have been necessary, and
could have been avoided in the first place.


PointedEars
 
D

Daz

Still, would you agree that wrong examples serve little practical purpose?

It depends on the circumstances. The idea was not to do the work for
the OP, but give an example that worked.
Why, the "implementation" is listen to mouse and keyboard events,
particularly mousedown, mouseup, click, keyup, keydown, and keypress.

The reason I suggested a timer, was so that if a user presses a key
down and holds it, the characters appear in the second box almost
instantly, and not when the key is initially pressed, or when the key
is depressed.

I don't see how this can be done using standard events, which is why I
asked for an example.

It does use system timer ticks which is the cause of the problem with it
when it comes to time-critical applications.

I'd hardly call my example "time critical". Sorry, I meant to ask what
setTimeout() uses, if not system ticks.

I read an interesting and IMHO sound argument about setInterval() vs.
setTimeout() in another thread here not long ago, but I don't have the
reference anymore. IIRC, it goes like this:

ECMAScript implementations are single-threaded. window.setInterval()
*attempts* to execute code every n milliseconds despite of that. Consider
that at that time another process/thread has priority, there are two
possibilities: either the application will execute the interval code
at the next available tick, or it will execute it at the next planned
opportunity, n milliseconds after the tick that could not be used.
Either way, the supposed calls are likely to accumulate here.

With setTimeout(), the application will have no choice but to execute it
at the next available tick; and only then the new timeout will be set.
So nothing can accumulate then.

That makes complete sense. Thanks for that. :)

I know this, although I don't see much of a point...

Not calling them as methods of Window objects assumes that the Global Object
or an unknown host object in the scope chain has such host-defined
properties. This would be error-prone.
I suppose you write all of your global variable and functions like
that too?

Of course not. Those are properties of the Global Object, not of a host
object that may or may not be available as such and may or may not share
the Global Object's properties. If I would do what you assume, that would
be error-prone, too.

The JavaScript 1.5 Reference already states:

,-<http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Gl...
|
| The [G]lobal [O]bject itself can be accessed by `this' in the global
| scope.

And rightly so; that is specified in ECMA-262 since its very first edition.

OK, that also makes sense. Thanks.

If you had the intention to give him a hint as how to solve his problem, it
would have been a Good Thing to post a reasonable example, even though the
original code was bad. That would not have involved "answering a whole head
of questions": a short note as to why it is bad along with the improved code
would have sufficed.

I agree with you there. I'll bear that in mind in the future.
That this newsgroup is not a newsgroup dealing primarily with HTML is a
null argument; we are attempting to write good code here, no matter the
language. In fact, it turns out that bad HTML, CSS etc. code often is
the cause of a script written in an ECMAScript implementation not to
function. You simply can't build a house on quicksand.

OK, I'll remember that too. :)

You can not know that.

I do, because the code I wrote worked. I could see that the method
being used was not going to achieve what the OP wanted. It was a with
accessing the form (which didn't exist), which was the source of why
it didn't do what he wanted at all. Granted, that decent markup could
have made a difference, but for my example, it was quite irrelevant.
In any case, I appreciate what you say and I will remember that in the
future.

[...]
Validation is an indicator of cluefulness - I couldn't agree more, but
we are talking about HTML validation for a JavaScript problem, when
you know as well as I do that wasn't the problem. Also, it's pretty
obvious that the OP isn't experienced.

So the logical course of action would be to deny them access to further
knowledge?

Of course not. But if you wrote an essay for everyone you helped, it
would be very time consuming. I originally only wanted to help with
getting what he wanted out of a form, so that he might be able to get
on the right track and perhaps be able to Google for further
assistance. I did get carried away, but tried to keep my response
minimal.

Proposing bad style is a Bad Thing, period.

Duly noted.

As I wrote, you could simply have refrained from replying to the OP.

I will do so in future.

A more knowledgable person than you would most certainly have replied
with a much better S/N ratio.

Ouch! Perhaps you mean "more educated"? I don't think I could explain
anything quite like you do.

No, it is a common misconception about the language, last but not least
transported or induced into the mind of beginners by bad books.

I know exactly where you're coming from... I've seen enough of them,
and I've spent a long time battling with what's right and what's not.

I won't quote the next bit of text, but I'll only ask where I can buy
your book? ;)

Your comparison was based on a (common) misconception.

I'll go with you on that one. I'd rather go with the crowd than
against them. ;)
But your statement at least implied this. Don't try to wind around that.

You're right (of course)! Sorry, I misread what you wrote.
So in your effort to "not do someone's homework for them", you've
actually gone and done it for them.
You are confused.

You're tellin' me!
I have never stated that I would "not do someone's
homework for them" (although I would probably not do that without proper
compensation in any form). However, you made it necessary to correct your
wrong example and false statements (or implications, if you wish). If not
only you but also others, including the OP, can learn from that, so be it.

That makes sense.
Still, the unlearning that is now required by them (again; if they even
recognized or understood the correction(s) which ended up being quite large
because of the sheer number of errors) would not have been necessary, and
could have been avoided in the first place.

I disagree with you there. My example was not meant to be a work of
art, and I did say that. If I wrote that crap and claimed it would
work with any browser, and it was standards-compliant, I'd be lying,
which is why I did mention it. However, I've still noted your
comments.
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <[email protected]>

Ouch, that had to hurt... Hehe.

Sorry for my initial response. I was kind of rattled about being
slammed the way I was. As you probably noticed with my comment to Lee
(a result from misreading his post), I'm not a fan of flaming anyone,
especially people who are learning. I have to admit, your second reply
was certainly enough to put the smile back on my face.

I can see you know what you're talking about, but does that mean that
everyone who wants to help others here has to have the same abilities
as you? I am not a guru, nor do I (or will I) ever claim to be,
however, I do like to help. Whilst I don't know as much as you, I am
aware of the standards, so I will ensure that any future posts are
gleaming.

Well, it was a pleasure debating with you (as one-sided as it was),
and although most of what we went over I already knew, I have learnt
some new tricks too, so thanks. :)

I'm not a complete idiot - there are bits missing...
 
L

Lee

Daz said:
I apologise, and take back my statement. It seemed to me as though you
were saying that what he was wanting to do was "pretty silly".

When you mentioned a class, I thought you were referring to a
JavaScript class (object), it never occured to me that you meant
educational class. Hopefully you can see where I was coming from,
taking your post in the context that I did.

I'll share the blame and will try to be more careful about using the
word "class" in the future.


--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top