brassmookie
brassmookie

Reputation: 417

Dynamically creating tens of thousands of form inputs

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?

Upvotes: 1

Views: 71

Answers (3)

R Greenstreet
R Greenstreet

Reputation: 740

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

Upvotes: 0

Zachary Haber
Zachary Haber

Reputation: 11027

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

Upvotes: 3

Stephen Duffy
Stephen Duffy

Reputation: 505

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;

Upvotes: 0

Related Questions