We help IT Professionals succeed at work.

Javascript array into text input

Why Dos the first piece of javascript work and the second one does not?  The second only adds the commas from the array and not the value:

<script>
var arr = ['society_one','society_two','society_three','society_four','society_five'];
for(var i=0;i<arr.length;i++){
    arr[i] = $('#'+arr[i]).val();
}
var society = arr.join(',');</script>
<script>
document.write('<input type="hidden" id="hiddenelement" name="custom_data[society_search_1]" value="'+society+'">');
</script>	

Open in new window


<script>
var arr = ['society_one1','society_twoa','society_threea','society_foura','society_fivea'];
for(var i=0;i<arr.length;i++){
    arr[i] = $('#'+arr[i]).val();
}
var societya = arr.join(',');</script>
<script>
document.write('<input type="hidden" id="hiddenelementb" name="custom_data[society_search_1]" value="'+societya+'">');
</script>	

Open in new window

Comment
Watch Question

Top Expert 2011

Commented:
Can you post the HTML that includes the fields that contain the values for "$('#'+arr[ i]).val();" ?

removing that portion of your code (where you reassign the array values), the code works fine in both cases... so it probably has to do with either the contents of your inputs or perhaps one of those items doesn't exist on your page due to a type so you end up with an undefined inside your array.
IT Expert
Top Expert 2009
Commented:
Works for me once I change to .html instead of document.write which you cannot do after load

I also changes society1 to societya

http://jsfiddle.net/mplungjan/8br6G/

Author

Commented:
mplungjan:

It works fine, one time.  The next time I come back to the page, nothing is added to the array.

If I move the code to a different part of the page it will work one time.  The next time I come back nothing will be entered into array.

I'm using the Expression Engine CMS if that makes a difference.
Michel PlungjanIT Expert
Top Expert 2009

Commented:
I have no experience with that. I would need to see the page in question

Author

Commented:
That worked, however, the array won't update unless you refresh the page, not if you hit submit.

Author

Commented:

That worked, however, the array won't update unless you refresh the page, not if you hit submit.
Michel PlungjanIT Expert
Top Expert 2009

Commented:
Not sure what you mean... Can you show me a page or rendered HTML.