简体   繁体   中英

Submit fields inside an iframe

I've got a page with a form where I load some elements in an iframe, one of them being an HTML page with another form inside it. I've tried a few things, but I can't seem to find a good way to submit both forms at the same time.

I saw a question here recommending to get rid of the child form and add its content to the parent dynamically, but I'd rathe not use that method because I need both the iframe (it sometimes loads other content) and the form (It's used in another context).

Target the form to the name of iframe

<iframe name="open"></iframe>

<form target="open"></form>

In simple terms: you can't split up a form in HTML. If you do:

<form>
    <input type="text" name="foo" value="bar" />
</form>
<form>
    <input type="submit" value="submit" />
</form>

Clicking the button will fire the 2nd form, and you wont see foo .

This is a simplified form of your case. The iframe splits your form up.

There is a way to stitch them back together but it's not at all easy.

Override the onsubmit handler of the form you're submitting (the one that has the button, if both have a button: do both). Cancel the event with event.preventDefault() .

Collect all the values you want to submit with JavaScript. All the values in the parent form, and all those in the iframe.

Now here you have two options. To submit your data you can either use AJAX or copy everything to a hidden form and submit that. The advantage of the latter is that it looks and feels like you're just submitting the form, the downside is that you have to copy all the form elements, that's tedious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM