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

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

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

Join form field string values using array and looping

Status
Not open for further replies.

LOOP123

Programmer
Mar 7, 2008
10
CA
Hello,

I'm hoping someone can help me with an easy solution. Here's what I'm trying to accomplish:

I have 5 form fields. Using javascript, each value is assigned to an array. I would like to use a loop to join each value (separated by a comma) and be assigned to a string variable (wholestring). The catch is that if any form field value is blank, it will be skipped. Here's what I've come up with so far, however, it's not working out for me:



var names = new Array();
var arraysize = names.length;

names[0] = frmOpt1.opt1N1.value;
names[1] = frmOpt1.opt1N2.value;
names[2] = frmOpt1.opt1N3.value;
names[3] = frmOpt1.opt1N4.value;
names[4] = frmOpt1.opt1N5.value;

var tellme = "";

for (var counter = 0; counter < arraysize; counter++){
if (names[counter] == "0"){
break;
}
else {
tellme = tellme + names[counter] + ", ";
}
}

var wholestring = tellme;

[/color red]

Any help would be greatly appreciated!

Thanks,
Dipesh.
 
I think your error could come from these 2 lines :
Code:
var names = new Array();
var arraysize = names.length;
When you initialize the "arraysize" variable, your array is empty. So the value of your variable is 0.
As is, the "for" loop will exit before the first iteration.

Move the line "var arraysize = names.length;" after the lines where you fill the array, it should work better.

Water is not bad as long as it remains outside human body ;-)
 
I'll try that, however, won't the following extract values to my form and assign values to the array before the loop code is excuted?


names[0] = frmOpt1.opt1N1.value;
names[1] = frmOpt1.opt1N2.value;
names[2] = frmOpt1.opt1N3.value;
names[3] = frmOpt1.opt1N4.value;
names[4] = frmOpt1.opt1N5.value;
[/color red]

Thanks!

Cheers,
Dipesh.
 
My name is MUD. After reading carefully, I see my error and you're totally right.

Thanks!

Cheers,
Dipesh.
 
Code:
var names = new Array();
for(var i = 1; i <= 5; i++){
 var fieldVal = frmOpt1["opt1N" + i].value;
 if(fieldVal != ""){
  names[names.length] = fieldVal;
 }
}

var wholestring = names.join(",");

[sub]Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.
[/sub]

Webflo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top