473,395 Members | 1,978 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Array of Text Box; knowing which one caused event

I am looking into the different techniques of handling arrays of edit
boxes in
Java Script. The first program below works fine. However, are there
better ways of
doing this, where the person writing the JavaScript doesn't have to
pass the index
in the "onChange" event name.
I thought that one might be able to use "this.value" or compare this as
indicated
in the second program, but it did not work.

Dr. Leff mf***@wiu.edu, ASsociate Professor of Computer Science,
Western Illinois
University, Macomb IL 61455 (309 367 0787 pager)
<HTML>
<HEAD>
<script Language="JavaScript">
document.write("array");
function Update(i) {
var aText = document.TF.Q[i].value;
document.TG.R[i].value = aText;
}
</script>
</HEAD>
<BODY>
<FORM name="TF">
<BR><INPUT TYPE=TEXT name="Q" onChange="Update(0)">
<BR><INPUT TYPE=TEXT name="Q" onChange="Update(1)">
<BR><INPUT TYPE=TEXT name="Q" onChange="Update(2)">
</FORM>
<FORM name="TG">
<INPUT TYPE=TEXT name="R" value="R1" >
<INPUT TYPE=TEXT name="R" value="R2">
<INPUT TYPE=TEXT name="R" value="R3">
</BODY></HTML>

This does NOT WORK:

<HTML>
<HEAD>
<script Language="JavaScript">
document.write("array 1");
function Update() {
var L = document.TF.Q.length;
alert("length is " + L+ " "+this.value);
for (i=0;i<L;i = i + 1) {

alert (" i is "+ i + "Q[i].value " + Q[i].value);
if (this.value == Q[i].value){
WhichOne=i;
}
}
alert ("whichONe is "+WhichOne);
var aText = document.TF.Q[WhichOne].value;
document.TG.R[WhichOne].value = aText;
}

The first alert shows an "undefined" for "this.value" I also tried
comparing
"this" to "Q[i]" directly with no good result.

I teach GUI with Java and have taught it using Microsoft API and MFC as
well
as X-Windows. These GUI all provide several ways to have one event
handler
for an array of controls and that event handler finding the control
that fired it.

Jan 17 '06 #1
4 9662
mf***@wiu.edu said the following on 1/17/2006 5:27 PM:
I am looking into the different techniques of handling arrays of edit
boxes in
Java Script. The first program below works fine. However, are there
better ways of
doing this, where the person writing the JavaScript doesn't have to
pass the index
in the "onChange" event name.


pass 'this' to the function and it will point at the element that
triggered it.

From there, you can get is name (if it has one), its ID (if it has
one), its value etc..

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jan 17 '06 #2
mf***@wiu.edu wrote:
<snip>
I thought that one might be able to use "this.value" or
compare this as indicated in the second program, but it
did not work. <snip> <FORM name="TF">
<BR><INPUT TYPE=TEXT name="Q" onChange="Update(0)">

<snip>

The function that you have given the name 'Update' is not an event
handler, it is a global function called from an event handler, and so
when it is executed the - this - keyword is a reference to the global
object, which does not have a - value - property.

The string value of an HTML event handling attribute is used as the
function body definition for a function object that the browser creates
internally and assigns to the - onchange - property of the corresponding
form control element. So the HTML attribute - onChange="Update(0)" - is
equivalent to doing:-

document.forms['TF'].elements['Q'].onchange = function(event){
Update(0)
};

- in most browsers, and:-

document.forms['TF'].elements['Q'].onchange = function(){
Update(0)
};

- in IE browsers and close imitators. (The difference being the event
handler function's formal parameter; 'event' in most browsers and
non-existent in IE browser. this reflects divergent handling of the
event objects, which IE makes available as a global variable and other
browsers pass as an argument to the event handler).

In javascript the value of the - this - keyword within a function is
determined (only) by how the function is called, and browsers
consistently call event handlers created from event handling HTML
attributes as methods of their associated elements, the equivalent of:-

document.forms['TF'].elements['Q'].onchange(); //or passing the event
//as an argument

This means that for the execution of the event handler the - this -
keyword is a reference to the form control element. However, the
internally generated event handling function calls your - Update -
function as a global function and so during its execution - this -
defaults to a reference to the global object.

If you want the function called from the event handler to have a
reference to the form control element on which the event was triggered
you may pass it that reference when the global function is called, and
you may get that reference with the - this - keyword in the event
handler. E.G:-

onChange="Update(this);"

- with the global function defined along the lines of:-

function Update(fieldRef){
...
}

- where the global function's - fieldRef - formal parameter receives the
reference to the form control element on which the event was triggered,
as a result of it having been passed as an argument in the -
Update(this); - function call.

Richard.
Jan 18 '06 #3
Thank you for the informative responses from Messrs. Cornford and Webb.
Using this information, I was able to use "Update(this)" and pick up
the
ID, etc. on the textbook in which the user entered text and left focus.
(See example below.)

However, is there any way we can avoid giving a unique ID or Value in
the HTML INPUT element.

We pass the textbox on which activity occurred to the procedure, by
writing onClick="Update(this)" And since all three text boxes are
named
Q, they form an array. Thus, I was hoping to compare the pointer
this with each successive element of TF.Q. I do this when I have
an array of buttons or other controls in Java.


<HTML>
<HEAD>
<script Language="JavaScript">
document.write("array");
function Update(i) {
alert (i.value+ "id " + i.id + "i.tabindex " + i.tabindex)
for (k=0;k<i.length;k++) {
if (i== TF.Q[k]){
alert ("equal ")
}
}
}
</script>
</HEAD>
<BODY>
<FORM name="TF">
<BR><INPUT TYPE=TEXT id="1" name="Q" onChange="Update(this)">
<BR><INPUT TYPE=TEXT id="2" name="Q" onChange="Update(this)">
<BR><INPUT TYPE=TEXT id="3" name="Q" onChange="Update(this)">
</FORM>
<FORM name="TG">
<INPUT TYPE=TEXT name="R" >
<INPUT TYPE=TEXT name="R" >
<INPUT TYPE=TEXT name="R" >
</BODY></HTML>

Jan 27 '06 #4
mf***@wiu.edu wrote:
Thank you for the informative responses from Messrs.
Cornford and Webb. Using this information,
Having posted my last response I considered following it up with some
comment on the code you were actually using. A shortage of available
time prevented me from doing so, but I suspect that if I had you would
not be asking this question now.
I was able to use "Update(this)" and pick up the
ID, etc. on the textbook in which the user entered
text and left focus. (See example below.)
Yes, you pass a reference to the specific form control as an argument to
the function call.
However, is there any way we can avoid giving a unique
ID or Value in the HTML INPUT element.
In HTML an ID attribute must be unique on any document. Names do not
have that same restriction (and for radio buttons to work together they
must have the same name attribute). It is not necessary to give any
element an ID, but form controls will not be 'successful' (their values
sent to the server upon submission) unless they have a name attribute.
We pass the textbox on which activity occurred to the
procedure, by writing onClick="Update(this)" And since
all three text boxes are named Q, they form an array.
Strictly it is a collection (so not a javascript Array, though a
collection is an array in the broadest sense of the word).
Thus, I was hoping to compare the pointer
Javascript doesn't have pointers as such. What we have is values that
refer to objects, how they refer is not specified (or important) and it
is normal (and sufficient) to refer to such values as references.
this with each successive element of TF.Q.
There you have a problem as - TF.Q - is not an ideal method of accessing
the collection. It assumes that TF is effectively a global variable that
has a value that refers to the form element. This is an IE proprietary
feature that is (more or less) reproduced in some other browsers, but
not all. The W3C HTML DOM specification defines a document.forms
collection as a convenience method for acquiring references to forms (by
name, ID and integer index) as a formalisation of a pre-existing feature
of browser object models. As a result it is standard and back-compatible
with all scriptable web browsers that expose forms for scripting.

Accessing a form with the name 'TF' would require:-

document.forms['TF']
-or:-
document.forms.TF

Each form element has (by W3C specification and again as a formalisation
of a pre-existing common feature) a property called - elements -, which
is a collection of all controls within the form. Form controls may be
accessed through the - elements - collection by integer index or by
name/ID, and when numerous controls share the same name the elements
collection returns a reference to another collection that is a
collection of all the like-named controls.

Your 'Q' control collection would be accessed as:-

document.forms['TF'].elemtns['Q']

(and/or dot notation variants)

However, all form controls have a property called 'form' that is a
reference to the form element that contains them, so as you are passing
a control to the function the easiest method of getting a reference to
the containing form (and so its - elements - collection) is through that
property:-

formControl.form.elements['Q']

This reference to the form element is anonymous, the form itself does
not need to have a name or an ID.

Also, as you want to acquire the collection of like-named controls to
which the control for which you have passed a reference belongs you can
anonymously look-up that collection as:-

formControl.form.elements[formControl.name]

(As the existence of a name attribute is required to create a like-named
collection of elements in the first place)
I do this when I have
an array of buttons or other controls in Java.
And you can do it successfully in javascript as well, as objects all
have unique identity that can be verified with either type-converting
comparison (==) or strict comparison (===) operations.
<HTML>
<HEAD>
Formally valid HTML is require to contain a TITLE element (it is
non-optional in an HTML document). It is important when (non-trivially)
scripting HTML DOMs that the DOM structure that the browser creates is
consistent (else the effort to produce cross-browser code is multiplied
many fold) and different browsers only create structurally consistent
DOMs when they are presented with structurally correct HTML mark-up. And
the best way of confirming that mark-up is structurally correct is to
validate it, for which it need to be formally valid in order to pass.
(Formal validity is a stricter requirement than structural correctness,
only structural correctness is necessary in order to avoid browsers
creating structurally inconstant DOMs.)
<script Language="JavaScript">
In formally valid HTML the SCRIPT element is required to have a TYPE
attribute, and if the TYPE attribute is present the (deprecated and
optional) LANGUAGE attribute is superfluous.
document.write("array");
function Update(i) {
Javascript has no notion of classes, but the concept of classes is often
used in script architecture. Because there is no syntax to define a
'class' the structures that are used to implement the concept of a
'class' are not inherently distinct. To mitigate this various naming
conventions are commonly used, and one (probably the most common) is to
give the primary Identifiers of structures implementing the 'class'
concept (usually a function that is to act as the class constructor) an
initial capital character, while using initial lower case characters for
all non-constructor and method functions. As this naming convention is
widely used (commercially), it is a reasonable idea to adopt it from the
outset.

The formal parameter of this function has been given the identifier -
i -, which says nothing about what the argument is. The argument is a
form control, possibly a specific type of form control, and it should be
identified as such by its identifier. This avoids confusion as to the
nature of the object referred to by that identifier.
alert (i.value+ "id " + i.id + "i.tabindex " + i.tabindex)
The 'i' in the property name 'tabIndex' is uppercase.
for (k=0;k<i.length;k++) {
The Identifier - k - has not been declared in this script (globally or
locally). It is good practice to explicitly declare all variables, local
or global, and doing so can avoid undesirable consequences of naming
collisions with the IE feature that makes IDed and named elements
accessible as global variables.

However, the general programming axiom that a variable should never be
given more scope that it absolute needs is as true in javascript as any
other language, and - K - does not need to exist in any scope outside of
this function. So it should be declared as a function local variable,
with the use of the - var - keyword. (it is particularly ill-advised to
use global variables as loop counters)

In using - i.length - you have suffered form using - i - as the
identifier for the form control. If you had used, for example, -
formControl - it may have been more obvious that the object referred to
by the identifier was singular and would not necessarily have a -
length - property, or that any - length - property it may have would be
unrelated to any colleciton of like named elements.

This is your primary problem this the code as it guarantees that the
code in the loop will never execute; - i.length - evaluates as the
value - undefined - and the comparison operator type-converts undefined
to the number NaN, and NaN always returns false from any comparison
operation for which it is an operand, the loop body is never executed.
if (i== TF.Q[k]){
Apart from the IE style reference to the form element, that comparison
would work, if the body of the loop was ever executed.
alert ("equal ")
}
}
}

</script>
</HEAD>
<BODY>
<FORM name="TF">


In valid HTML the opening FORM tag is required to include an ACTION
attribute.

Your modified function may resemble:-

function update(formControl){
var k, controlCollection;
alert(formControl.value +
"id " + formControl.id +
"formControl.tabIndex " + formControl.tabIndex
);
if(
(controlCollection = formControl.form.elements[formControl.name])&&
(controlCollection != formControl) // In case there is only one
// control with this name.
){
for(k = 0;k < controlCollection.length;++k){
if(formControl == controlCollection[k]){
alert("equal ");
}
}
}
}

Richard.
Jan 30 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Mike | last post by:
I have a combo box and a text box. Text to be display will be contigent upon what is selected via the combo box. How do I do this? I put the following code in the text box object: var a =...
2
by: kc | last post by:
Hello All I put this array on the document level of an Acrobat form var gmagazine = new Array gmagazine = "48" gmagazine = "12" gmagazine = "20" I then put this on a drop down list field...
1
by: David Smith | last post by:
What I want to be able to do: A textbox is available that the user can enter information into. Specifically (for the purposes of this post), the user is asked to enter a number, and that number...
3
by: Michael Glass | last post by:
I'm working on an ASP.Net web app using VS2005 and the .Net 2.0 framework, and I have a serious problem with the page I'm currently working on. The page has, among other things, two FormViews and a...
6
by: Mike | last post by:
I am just beginning with VB and had been using a crippled version of VB 6.0 which works fine except there's limited information resouces with it. So, like a good scout, I got a learning edition of...
4
by: Rich | last post by:
Hello, I have 3 textboxes and 1 combobox on a form. On entering the control I want to select all the text. I can make an array of textboxes like this: Dim arrTxt As TextBox() = {txt1, txt2,...
4
by: Kev | last post by:
Hello, I have an Access 2003 database running on an XP network. I have a datasheet subform containing a 28 day roster - shift1 to shift28. Each record has 1 RosterEmpID, 1 EmployeeNumber, 28...
4
karthickbabu
by: karthickbabu | last post by:
Hi Is Possible to store a value to declared Variable from Text Box at run time. I want to store a value from Text Box in 2 dimension array. First Value can be sotred in variable(0,0). ...
2
by: yeshello54 | last post by:
so here is my problem...in a contact manager i am trying to complete i have ran into an error..we have lots of code because we have some from class which we can use...anyways i keep getting an error...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.