• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 315
  • Last Modified:

javascript - converting from var array to string

I'm using a javascript to populate an array defined as:

var typearray = new Array();

then, I need to set a hidden field in the html to this value.  I tried:
 document.sortForm.typearray.value = typearray;


document.sortForm.typearray.value = typearray.toString();

but when I display the value it shows as [object] and when I try to use it in my servlet the value is garbage.

How do I pass this array as a string by using hidden fields in my html?

  • 3
1 Solution
You want to put an array (a collection of objects) into a hidden field (a single object)?

I think you'll need to do something like:

value = '' ;
for( int i = 0 ; i < typearray.length ; i++ )
    if( i > 0 )
        value += ',' ;
    value += typearray[ i ] ;
document.sortForm.typearray.value = value ;

basically you can't do what you're trying to do, so that code will comma separate the values in the array, and set the hidden field to that value

So if you had:

valuearray = new Array( 3 ) ;
valuearray[ 0 ] = 'hello' ;
valuearray[ 2 ] = 'there' ;
valuearray[ 3 ] = 'tim' ;

the hidden field will be set to

You could try this javascript array method. I saw this in a book.  
document.sortForm.hidden.value = typearray.join();  
or use
document.sortForm.hidden.value = typearray.join(separator);  
Now, do want us to give code for parsing this value on the JSP side ?       rrz
> document.sortForm.hidden.value = typearray.join();  

Nice! :-D
Something like this;
var typearray = new Array();
var oSpan = document.getElementById("");
oSpan.innerHTML = typearray [0];  // append each array element to the span's contents
and so on---
Did you get the idea?

Featured Post

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now