Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate array style form fields with jquery

I would like to POST a form with attributes as described here (MVC friendly array): https://stackoverflow.com/a/5003686/1246219 The reason I want to POST a form rather than using ajax is that the result is a file for download, i.e.there is no other reason for using a form.

However I have a javascript array containing the values (integers) that I would like to submit. The only ways to achieve this that I can think of are either to loop through and create input elements for each entry, or I could just populate a single form field with a comma delimited string and parse it server side. Is there a better way?

UPDATE - If anyone is interested I have ended up with the loop approach, and happened to write it with d3 instead.

var selected = [1,2,3];
var selectionBinding = d3.select("#myForm").selectAll("input[name='myField']").data(selected);
selectionBinding.exit().remove();
selectionBinding.enter().append("input")
                .attr("type", "hidden")
                .attr("name", "myField")
                .attr("value", function (data) { return data });
$("#myForm").submit();
like image 454
Andrew Avatar asked May 12 '26 03:05

Andrew


1 Answers

My suggestion would be to create a regular Javascript Array with data and have a form with input type text. When you submit the form set the value of the input text as JSON.stringify(myArray)

like image 123
closure Avatar answered May 13 '26 16:05

closure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!