views:

39

answers:

1

Hello,

I assume this one is rather a JavaScript/jQuery/DOM question than a Rails question, but it's all due to the way I implemented it in Rails.

I am trying to upload files while creating a new object (auction). While the user inputs some data, he shall also have the possibility to upload multiple photos.

The main problem is, that the files should be uploaded while filling out the form. And the form is a tabbed one, so the photos are on tab 3 of 5 and all tabs sit within the overall create form. That means, that the upload form has to be (DOM position) within the main form for creating the object, which is not allowed by the HTML specification.

To avoid nesting forms I tried to jQuery.clone() the file field when submitting the photo first, so I can create the upload form on the fly - but this didn't work, as JS doesn't seem to be able to access the value of a file field.

So my question is: how could I implement such a "submit form to hidden iframe" thingy, when I can't avoid to place the upload-only form within another form, from a DOM point of view? Does anyone know a good hint or something?

Thanks in advance for your help

Arne

+1  A: 

Ok, assuming you have one form, you can do the following:

  • Set the target of your form to point to the name of the Iframe. The POST with the file upload will occur in the background, targeting the Iframe.
  • Use window.setTimeout(function() {document.form1.target=''},1) to clear the target after when your form submits.
  • Continue using the form as normal.

If course it's a little easier if you have multiple forms, that way you can just point the file upload form to that target by itself.

EDIT - Try this:

<form id="upload-form" target="myiFrame"><input type="file" /></form>
<form action="/model/create"></form>
<iframe name="myiFrame" src="/model/upload"></iframe>
Diodeus
Hi, thanks for your quick answer. But there's still this one problem: In the DOM the upload form still sits within the main form. Posting to the iFrame is the way I want to implement it, but the source would still be <form action="/model/create"><form id="upload-form" target="myiFrame"><input type="file" /></form></form><iframe src="/model/upload"></iframe>
arnekolja
The HTML spec does not allow you to nest forms.
Diodeus
Hey, I think I misunderstood you before. Didn't notice that you meant changing the main form to reflect the upload url temporarily. I did it this way now and it works perfectly! Using the onchange event of the file field I change the form's action url to upload, then submit the form and change the action url back to create. It works like a charme, thanks!
arnekolja