Javascript array from form

Hi all

Cant seem to get this working how I want it, any help appreciated

Ive a realtime input form (users can add extra lines using a javascript function) that needs to return to the database on submit, this works fine. in the next section of the form I have need to read the values put in the first section for inclusion in a select box, again using JS.

Al lthe abouve work fine providing that I use the variable for the name of the forms elements etc.

however I really need to use the format variable[y] and thats where everything stops working.

So, in section 1 of my form that the javascript writes I have


   newCell2.innerHTML = '<input type="hidden" name="building[' + (numRows) + '][id]"  ' + (buildid) + ' /><input type="text" name="building[' + (numRows) + '][name]" ' + (buildingname) + ' />';

numRows = the current row number of the table, it counts up as people add new lines to the form.

buildid & buildingname = text strings that add a value to the input tags.

then in my second section Im trying to read in the values of these arrays using.


buildingarr = document.getElementsByName("building[]");
  opts = null;
  for(var i=0;i<buildingarr.length;i++){
    opts = opts +'<option value="' + (buildingarr[i][name].value) +'">' + (buildingarr[i][name].value) +'</option>';
   } 
    newCell5.innerHTML = '<select name="room[' + (numRows) + '][building]">' +
         opts +
        '</select>';

TIA

Don’t reference the form fields using the name attribute from JavaScript - reference them by their id instead and then you can use whatever the server side processing need the name to be without it interfering with the JavaScript.

This code could be hard to maintain. Since you intended to gather all the input value for the options.
Just go for it, and later you can filter node attributes to build your select element.

buildingarr = document.querySelectorAll(“#section1 input[type=text]”);
for (var i = 0, len = buildingarr.length; i < len; i++) {
var value = buildingarr[i].value;
opts = opts + ‘<option value="’ + value + ‘">’ + value + ‘</option>’;
}

Don’t try to add options to a select that ewat - use new Options(txt,val) instead

new Option(txt,val)