1

I am attempting to dynamically create form data with the following method, where input_values is an array of values:

    for (var i in input_values) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = "lat_lngs[]";
        input.value = input_values[i];
        document.getElementById('ride_form').appendChild(input);
    }

This works fine for most situations. However, the input_values array contains tens of thousands of entries. When the number of inputs goes above 3000 or so, the browser starts to hang. Is there another method that can achieve this result? Or is this simply too much to ask of the DOM?

brassmookie
  • 349
  • 2
  • 13
  • 2
    Why in the world would anyone need a form with that many inputs? – j08691 Apr 28 '20 at 20:12
  • 2
    If they are all input hidden, you had better send them via AJAX. See FormData object: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects – mateleco Apr 28 '20 at 20:13

3 Answers3

3

It is far too much for the DOM. I'd suggest some type of list virtualization if you expect users to actually fill out the form. (Although I think 3000 inputs is too long for users too fill out too)

If you are just sending data, use Axios or the fetch api to send the data directly. You can mimic everything a form sends out.

axios post request to send form data


Since some of your data is in the form normally as well, it looks like you can just use FormData from your element to start with and then append the rest of your data.

let myForm = document.getElementById('ride_form');
let formData = new FormData(myForm);

https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
0

Taking into account Zachary's answer that 3000 might be too much for the dom, Ive sometimes found injecting into innerHTML can be smoother. I cant say it will be worth trying but it may be if you go:

var ihtml='';
for (var i in input_values)
   ihtml+=   '<input type="hidden" name="lat_lngs[]" value="'  +
              input_values[i]  +  '" />';
} 
document.getElementById('ride_form').innerHTML+=ihtml;
Stephen Duffy
  • 467
  • 2
  • 14
0

If you have access to the back end, and understand the structure of the data going into/being saved by the form, you can build a script to push things directly into the database as a 'seeds' file, similar to this:

https://github.com/rmgreenstreet/custom-forms/blob/master/seeds.js

R Greenstreet
  • 719
  • 6
  • 21