【问题标题】:Submit form in parent window from popup?从弹出窗口在父窗口中提交表单?
【发布时间】:2013-04-24 09:16:45
【问题描述】:

我有 2 个这样的 HTML 文件。

parent.html

<form method='get' action=''>
    <input type='hidden' name='something'>
    <input type='button' name='submit' value='Submit' onclick='newwindow=window.open("child.html","popup","height=150,width=200");'>
</form>

child.html

Enter Something Here<br />
<input type='text' name='somethingelse'>
<input type='button' name='submit' value='OK'>

当用户点击parent中的提交按钮时,会出现一个新的弹出窗口并要求他输入内容。

谁能告诉我如何将 input[somethingelse] 的值从 child 在用户点击OK后输入[something]并在parent中提交表单?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    您可以通过window.opener.document在父窗口中获取对表单的引用,如下所示:

    var form = window.opener.document.getElementById("theFormID");
    

    (您可以为表单提供一个 ID,尽管还有其他方法可以做到这一点。)

    然后您可以访问该表单中的字段,当然还可以设置其.value 属性,然后您可以通过其.submit() 函数提交表单。

    但公平的警告:用户不喜欢弹出窗口。如果有任何方法可以将其他字段合并到表单中,我建议您改为这样做。

    这是一个完整的例子:Live Copy | Source | Source of popup

    主页:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    </head>
    <body>
      <form id="theForm" action="" method="GET">
        <input type="text" id="theField" name="theField">
        <br><input type="submit" value="Send" onclick="window.open('/urawum/1','','height=400,width=400'); return false;">
      </form>
    </body>
    </html>
    

    弹出窗口:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    </head>
    <body>
      <p>Please fill in more information:</p>
      <input type="text" id="thePopupField">
      <br><input type="button" value="Send Form" onclick="doTheSubmit();">
      <script>
        function doTheSubmit() {
          var doc = window.opener.document,
              theForm = doc.getElementById("theForm"),
              theField = doc.getElementById("theField");
          theField.value = document.getElementById("thePopupField").value;
          window.close();
          theForm.submit();
        }
      </script>
    </body>
    </html>
    

    如果你运行它,你会发现当你点击主页上的Send 时,它会弹出。如果您在弹出窗口中填写一个值并单击Send Form,则弹出窗口消失并提交表单。您可以知道表单是使用该值提交的,因为我使用了method="GET",因此您可以在结果页面的 URL 中的查询字符串中看到theField=yourValue。例如,如果您在弹出窗口中键入“我的值”,您将在表单提交后在主页中看到 URL http://jsbin.com/abiviq/1?theField=my+value。 (不过你的表单大概使用POST而不是GET,我只是用GET来演示。)

    【讨论】:

    • 这是一个很好的答案!也非常感谢您的解释。我已经尝试过了,它完全按照我想要的方式工作。
    • @user433531:很好,很高兴有帮助!
    • @Lukasz Koziara:谢谢,但如果我想这样缩进,我会的。最好的,
    【解决方案2】:
            $('#popupformid').submit(function() {
    
                    var myVar = $('#somethingelseid').val();
                    $('input:text.something').val(myVar);
                    document.getElementById("formID").submit();
             });
    

    【讨论】:

    • OP 对 jQuery 只字未提。请不要发布非 jQuery 问题的仅 jQuery 答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    相关资源
    最近更新 更多