How to add a hidden list of IDs to a form in Javascript?
I've got a simple form in html:
<form action="" method="post">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this stuff">
</form>
I also have a file upload on the page, which handles uploads using ajax and adds the files to a mongoDB. The file upload returns the mongoDB id of the file (for example 12345
) and I want to add that id to the form as a hidden field so that the id is POSTed to the server upon submitting the form. Since the user can add multiple files though, I want to add a list of id's to the form.
I found how I can add one hidden field to a form from javascript, but this always handles a single field, not a field with multiple values. So I thought of adding a checkbox field to the form so that I can submit multiple values in one element, but it kinda feels like a hack.
Can anybody hint me in the right direction on how I can add a hidden list of values to a form using Javascript? All tips are welcome!
[EDIT] In the end I would like the form to look something like this:
<form action="" method="post">
<input type="hidden" name="ids" value="[123, 534, 634, 938, 283, 293]">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this stuff">
</form>
I am not sure if I understand your question correctly, so I may just be guessing here.
Try adding multiple hidden inputs with a name such as ids[] so that they will be posted to the server as an array.
Example:
<form action="" method="post">
<input type="hidden" name="ids[]" value="123">
<input type="hidden" name="ids[]" value="534">
<input type="hidden" name="ids[]" value="634">
<input type="hidden" name="ids[]" value="938">
<input type="hidden" name="ids[]" value="283">
<input type="hidden" name="ids[]" value="293">
<input type="submit" value="Save this stuff">
</form>
Why not simply concatenating all the ids into a string like so "123,456,890,..etc" and then adding them as a value to ids inupt. When you need them, simply split by ',' which would give you an array with ids?
Todo so only with javascript something like this should work
var elem = document.getElementById("ids");
elem.value = elem.value + "," + newId;
Do you mean that for each time the user clicks the 'upload' button you need to add a hidden field to the form? Can you post the entire form, that should clear things up...
[Edit] you could store the id's in an Array, everytime an id should be added to the hidden field's value you could do somthing like:
$('#ids').attr('value', idArray.join());
I'm just typing this out of the box so excuse any little errors
链接地址: http://www.djcxy.com/p/83478.html