2017-03-04 56 views
0

我想在iframe中填充我的表单。我需要在文本框中输入一个值,然后从下拉菜单中选择一个值。在iframe中的asp.net javascript getelementbyid

WebForm1的

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 

    <script src="admin-lte/js/app.min.js"></script> 
    <script src="Scripts/jquery-2.1.3.min.js"></script> 

</head> 
<body> 
    <style type="text/css"> 
    body {scrolling:no; 
} 
    iframe {position:absolute; 
    z-index:1; 
    top:0px; 
    left:0px; 
} 
</style> 
    <form id="form1" runat="server"> 

    <iframe id="frame1" src="WebForm4.aspx" width="100%" height="100%" frameborder="0"> 
</iframe> 

    <script> 
     function getElementWithinIframe() { 


      var iframe = document.getElementById('frame1'); 
      var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document; 

      var quantity = innerDoc.getElementById("txtQuantity"); 
      quantity.value = "5"; 

      var submit = innerDoc.getElementById("btnQuantity"); 
      submit.click(); 
     } 
    </script> 

    </form> 
</body> 
</html> 

webform4

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 

     <asp:DropDownList ID="ddlProd" runat="server"> 
      <asp:ListItem>Product1</asp:ListItem> 
      <asp:ListItem>Product2</asp:ListItem> 
      <asp:ListItem>Product3</asp:ListItem> 
      <asp:ListItem>Product4</asp:ListItem> 
      <asp:ListItem>Product5</asp:ListItem> 

     </asp:DropDownList> 
     <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox> 

     <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> 

    </div> 
    </form> 
</body> 
</html> 

这不起作用。我错过了什么?

我已经通过了多篇文章,但我认为我没有得到它。

Javascript - Get element from within an iFrame

How to pick element inside iframe using document.getElementById

任何帮助表示赞赏。

- 感谢

回答

0

在您使用btnQuantity父的JavaScript,而在WebForm4.aspx按钮的ID为btnSubmit。因此,将脚本更改为:

var submit = innerDoc.getElementById("btnSubmit"); 

然后在某个地方调用函数,无论是在按钮单击还是页面加载。

<input type="button" onclick="getElementWithinIframe()" value="ClickMe"> 

<script> 
    $(document).ready(function() { 
     setTimeout(function() { getElementWithinIframe(); }, 250); 
    }); 
</script> 
+0

好吧,那是我的错。但仍然无效。正如你所说,我改变了脚本。文本框(txtQuantity)没有被填充。 –

+0

它在我的测试环境中执行。您是否在“WebForm4”后面的代码中清除了“txtQuantity”的内容,可能是因为您还在进行表单发布。 – VDWWD

+0

而你必须在某处调用'getElementWithinIframe'。 – VDWWD