473,910 Members | 4,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with loop

Hi there

I have following function which is called on load of page.
function checkFieldConte nt(form) {
var field;
for(i = 0; i < form.elements.l ength; i++) {
field = form.elements[i];
if (field.type == 'text') {
alert(field.nam e);
// checkSearchInpu t(field);
}
alert('after');
}
alert('end');
}

Like this it works perfect but as soon as my own function is called ->
checkSearchInpu t(field); it's only going one time through the loop,
checkSearchInpu t calls various subfunctions and at the moment does not
return anything. I'm not really into js and confused about when I need
to return true or false on a functions call. I tried it with a return
value (true or false) but it didn't change anything. Of course function
checkSearchInpu t for itself works without errors...

Thanks a lot for your appreciated help!

sg2923

Aug 18 '06 #1
12 1485
us****@gmx.net wrote:
<snip>
function checkFieldConte nt(form) {
var field;
for(i = 0; i < form.elements.l ength; i++) {
field = form.elements[i];
if (field.type == 'text') {
alert(field.nam e);
// checkSearchInpu t(field);
}
alert('after');
}
alert('end');
}

Like this it works perfect but as soon as my own function is called ->
checkSearchInpu t(field); it's only going one time through the loop,
checkSearchInpu t calls various subfunctions and at the moment does
not return anything.
So you though you would post the code that works an leave everyone to
guess as to what is in the code that actually causes the problem?

In any event; you have not declared your loop counter - i - as a
function local variable (so it is effectively global). If any of the
functions called from within the loop use a similar - i - variable that
is also not declared as a function local variable, and any set its
value beyond the length of the elements collection, the loop will be
terminated on the next occasion the value of the global - i - variable
is checked.
I'm not really into js ...
<snip>

Using global variable where local variables should be used is a fault
in programming in general, so not related to JS as such.

Richard.

Aug 18 '06 #2
us****@gmx.net writes:
I have following function which is called on load of page.
function checkFieldConte nt(form) {
var field;
for(i = 0; i < form.elements.l ength; i++) {
Here "i" is not declared to be a local variable. That means that
it is created as a global variable. You should always declare
your variables to have only as much scope as needed, i.e.,
change this to:

for(var i = 0; i < form.elements.l ength; i++) {
// checkSearchInpu t(field);
Most likely you have a similar loop in the "checkSearchInp ut", which
means that the value of the global "i" variable is changed by the call
to something larger than "form.elements. length". Fix that method too.

(If a call to a function makes your script break, it might be a good
idea to include that function when you ask for help :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 18 '06 #3
wrote on 18 aug 2006 in comp.lang.javas cript:
I have following function which is called on load of page.
function checkFieldConte nt(form) {
var field;
for(i = 0; i < form.elements.l ength; i++) {
field = form.elements[i];
if (field.type == 'text') {
alert(field.nam e);
// checkSearchInpu t(field);
}
alert('after');
}
alert('end');
}

Like this it works perfect but as soon as my own function is called ->
checkSearchInpu t(field); it's only going one time through the loop,
checkSearchInpu t calls various subfunctions and at the moment does not
return anything. I'm not really into js and confused about when I need
to return true or false on a functions call. I tried it with a return
value (true or false) but it didn't change anything. Of course function
checkSearchInpu t for itself works without errors...
You should never call a variable "form".
Treat form as a reserved word.

In this code you hurt yourself,
as you fill the form with a external value
of a variable called field
that probably is defined as a field
and not as a form.
Try:

=============== ===============
<script type='text/javascript'>

function checkFieldNames (myForm) {
var myForm = document.getEle mentById('thisF orm')
var myField;
for(var i = 0; i < myForm.elements .length; i++ ) {
myField = myForm.elements[i];
if (myField.type == 'text')
alert(myField.n ame);
}
}

</script>

<body onload='checkFi eldNames("thisF orm")'>

<form id='thisForm'>
<input name='t1'>
<input name='t2'>
<input type='submit' name='skipped'>
<input name='t3'>
</form>
=============== =============== ===

The for(i = 0;...
should be for(var i = 0;...
but that will only cause problems
if you have a global variable i,
and even then the above function will not be affected.

The type declaration in <input type='text' is default.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 18 '06 #4
On 18/08/2006 19:00, Evertjan. wrote:

[snip]
You should never call a variable "form".
Treat form as a reserved word.
Don't be silly. The only place (that comes to mind) where "form" occurs
as a predefined identifier is as a property of form controls. Unless one
were to use a with statement - a generally discouraged practice - that
identifier would not otherwise appear without being accompanied by an
object reference and a dot (.) operator. In short, there's no ambiguity,
and no reason to consider it reserved.
In this code you hurt yourself,
as you fill the form with a external value
of a variable called field
that probably is defined as a field
and not as a form.
Sorry, but that didn't make much sense.

[snip]
function checkFieldNames (myForm) {
var myForm = document.getEle mentById('thisF orm')
Hmm? You declare function with a formal argument called myForm, then
create a local variable with the same name and assign to that a
reference to a form element (using getElementById rather than the forms
collection)?
var myField;
for(var i = 0; i < myForm.elements .length; i++ ) {
myField = myForm.elements[i];
if (myField.type == 'text')
alert(myField.n ame);
}
}
[snip]

So are you suggesting that making unnecessary changes to identifiers is
going to fix the OP's code? I came to the same conclusion as the
proceeding four posts: a conflict with the global loop index is the most
likely cause for the loop to terminate early.

Mike
Aug 18 '06 #5
Michael Winter wrote on 18 aug 2006 in comp.lang.javas cript:
>function checkFieldNames (myForm) {
var myForm = document.getEle mentById('thisF orm')

Hmm? You declare function with a formal argument called myForm, then
create a local variable with the same name and assign to that a
reference to a form element (using getElementById rather than the
forms collection)?
I agree, this is not very logical.

I ment:

myForm = document.getEle mentById(myForm )

[also the var is not necessary, even in IE, as the variable myForm is
already "auto-local-varred" as function argument]
So are you suggesting that making unnecessary changes to identifiers
is going to fix the OP's code?
No. I would not dare. I am not even convinced it needs fixing.
I came to the same conclusion as the
proceeding four posts: a conflict with the global loop index is the
most likely cause for the loop to terminate early.
No, I do not think that is possible.

The loop variable i could influence the value of a global i setting it
at it's final loop value.

The case of the value of a global i influencing the loop i is
[nearly?] impossible, as one would have to imagine a interfering
setTimeout running at the "same" time in this single treaded javascript
environment.
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 18 '06 #6
"Evertjan." <ex************ **@interxnl.net writes:
Michael Winter wrote on 18 aug 2006 in comp.lang.javas cript:
myForm = document.getEle mentById(myForm )
It's a waste of time to send the string id of the element as an argument
if you have the form element itself at hand. You typically have that
when calling from an event handler on a form control.
>I came to the same conclusion as the
proceeding four posts: a conflict with the global loop index is the
most likely cause for the loop to terminate early.

No, I do not think that is possible.
The loop variable i could influence the value of a global i setting it
at it's final loop value.
Yes. And any other assignment to the global "i" variable would also
affect the condition of the loop.
The case of the value of a global i influencing the loop i is
[nearly?] impossible, as one would have to imagine a interfering
setTimeout running at the "same" time in this single treaded javascript
environment.
Or assign directly to "i" from inside the loop, e.g., in the called
function. Since "i" is global, that's easily done, and if a loop variable
is global in one place, it's likely that it is in other places as well.

Also, all the usualq Javascript implementations are single threaded,
so a setTimeout wouldn't interrupt a running loop.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 18 '06 #7
Lasse Reichstein Nielsen wrote on 18 aug 2006 in comp.lang.javas cript:
>The case of the value of a global i influencing the loop i is
[nearly?] impossible, as one would have to imagine a interfering
setTimeout running at the "same" time in this single treaded javascript
environment.
Or assign directly to "i" from inside the loop, e.g., in the called
function. Since "i" is global, that's easily done, and if a loop variable
is global in one place, it's likely that it is in other places as well.
I do not see any difference, as, once inside the loop, the i is affected
independent if it were globally declared or not.

Only if the global is called by it's exclusive global name:

window.i

then there would be a difference, but who would do that and forget to
do for(var i=0;... ?
Also, all the usualq Javascript implementations are single threaded,
so a setTimeout wouldn't interrupt a running loop.
That is what I implied, Lasse.
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 18 '06 #8
On 18/08/2006 21:21, Evertjan. wrote:
Lasse Reichstein Nielsen wrote on 18 aug 2006 in
comp.lang.javas cript:
>"Evertjan." <ex************ **@interxnl.net writes:
[snip]
>>The case of the value of a global i influencing the loop i is
[nearly?] impossible, as one would have to imagine a interfering
setTimeout running at the "same" time in this single treaded
javascript environment.

Or assign directly to "i" from inside the loop, e.g., in the called
function. Since "i" is global, that's easily done, and if a loop
variable is global in one place, it's likely that it is in other
places as well.

I do not see any difference, as, once inside the loop, the i is
affected independent if it were globally declared or not.
Not necessarily. See below.
Only if the global is called by it's exclusive global name:
Again, not so. Consider:

function a() {
for (i = 0; i < 5; ++i) {
b();
}
}

function b() {
for (i = 0; i < 10; ++i) {
/* ... */
}
}

In both functions, the variable i is global. Upon the first call to the
second function, b, that same global is incremented to 10. Once
execution resumes in the first function, a, and the loop repeats, the
condition will evaluate to false and the loop will exit. This is
probably what has happened to the OP; if one loop uses a global index,
it not unreasonable to assume that other loops within the script will do
the same.

[snip]

Mike
Aug 18 '06 #9
Michael Winter wrote on 18 aug 2006 in comp.lang.javas cript:
>I do not see any difference, as, once inside the loop, the i is
affected independent if it were globally declared or not.

Not necessarily. See below.
>Only if the global is called by it's exclusive global name:

Again, not so. Consider:

function a() {
for (i = 0; i < 5; ++i) {
b();
}
}

function b() {
for (i = 0; i < 10; ++i) {
/* ... */
}
}

In both functions, the variable i is global. Upon the first call to the
second function, b, that same global is incremented to 10. Once
execution resumes in the first function, a, and the loop repeats, the
condition will evaluate to false and the loop will exit. This is
probably what has happened to the OP; if one loop uses a global index,
it not unreasonable to assume that other loops within the script will d
True, I would have suspected some form of cascading,
but that does not seem to be the javascript way.

testing:

=============== =============== =
function a() {
for ([var] i = 0; i < 5; ++i) {
b();
document.write( i+' ')
}
}

function b() {
[var] i = 10;
}

a()
=============== ===============

where [var] means the adding or not of the var.

if either [or both] var is added the the count goes 0 1 2 3 4,
where i expected only the varring of inner i to be significant.

Thanks, a bit wizer again.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Aug 18 '06 #10

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

Similar topics

0
2949
by: Charles Alexander | last post by:
Hello I am new to php & MySQL - I am trying to retrieve some records from a MySQL table and redisplay them. The data in list form looks like this: Sample_ID Marker_ID Variation G23_NA17192.fsa rs7374540 A/C I23_Control.fsa rs7374540 C/C
4
4407
by: JP SIngh | last post by:
Thanks to Manohar for writing the basic code for displaying the managers and the employees in a tree like structure. I have adapted the code below but it gives me an error "exception occcured" after the first recursion. Any ideas what can be done to make the following code work. Thanks
2
2494
by: Xiaozhu | last post by:
I trid to use icc -axW to optimize the code, but it becomes much slower... 8sec/37sec before and after using this option. my cpu is Intel(R) Pentium(R) 4 CPU 2.40GHz the test code is just one loop: for(int i=0; i<100000000; i++){ p=sin(double(i)); }
5
3346
by: Carmine Cairo | last post by:
Hi, I'm working on a project and today I've note a little problem during the compile fase. Here a little piece of code: // 1st version welldone = 0; size = p->getSize(); backbone = new rightType;
8
2396
by: Jeff | last post by:
Hello everybody, I was doing one of the exercises in the K&R book, and I got something really strange. Here's the source code: /* * Exercise 2-2 from the K&R book, page 42 */ #include <stdio.h>
47
5310
by: fb | last post by:
Hi Everyone. Thanks for the help with the qudratic equation problem...I didn't think about actually doing the math...whoops. Anyway... I'm having some trouble getting the following program to work. I want to output a bit pattern from base 10 input. All I get is a zero after the input...I've looked over the code but can't see the problem...any ideas? /* display the bit pattern corresponding to a signed decimal integer */
8
6473
by: koorb | last post by:
I am starting a program from a module with the Sub main procedure and I want it to display two forms for the program's interface, but when I run the program both forms just open and then program closes. Dim FORM1 As New Form1 Dim FORM2 As New form2 Sub main() FORM1.Show() FORM2.Show()
11
2120
by: felixnielsen | last post by:
What i have is not even a real problem, but i hope someone can help anyway, but first a piece of code_ @code start const unsigned short Size = 2; // 2^N std::bitset<Size*Size*Size> YZ; std::bitset<Size*Size*Size> XZ; std::bitset<Size*Size*Size> XY; std::bitset<Size*Size*Size> V; union {
1
1540
by: Promextheus Xex | last post by:
First php post... Hi there, I'm writing some code for my website to list people listening to my music. I have a loop for an array that dosen't seem to display all people. most of the time it resuses to go past 11 even though there are more people. I've created a small loop just to list the IP addresses as a test, which works. ie:
5
3464
by: =?Utf-8?B?Z215ZXJz?= | last post by:
Hello, I am attempting to start a cmd.exe process and pass several .vbs scripts (with additional parameters) and then read the output from the scripts and make "notes" in a DataTable (the "notes" not being the issue). Beginning with... Dim objProcess As Process Dim objProcessStartInfo As New ProcessStartInfo
0
10037
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11349
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10921
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11055
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9727
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8099
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7250
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5939
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4337
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.