访问iframe中选定的单选按钮值

时间:2013-02-22 13:28:39

标签: javascript html

我写了代码。我在哪里写一个表格,其中有一长串的单选按钮内容列在'iframe'中,如下所示:

<form name="iframeform" method="POST" action="http://localhost/cgi-bin/run">
    <tr>
            <td><iframe id="macList" src="http://localhost/macinfo" style="width:1000px;height:160px">
            </iframe></td>
    </tr>
    <tr>
            <input type="hidden" name="macaddr" value="">
            <td><input type="submit" name="macselect" value="Continue" id="stdbtn" onclick="getIframeContent()"></td>
    </tr>
</form>

'iframe'指向macinfo页面的代码如下:

<html>
<body>
<table>
<tr>
<td><input type=radio name=mac value=E8:B7:48:7B:C0:4A>abc.example.com</td>
</tr>
<tr>
<td><input type=radio name=mac value=00:17:08:5A:81:CF>xyz.cisco.com</td>
</tr>
....
</table>
</body>
</html>

如何编写“getIframeContent()”函数来获取所选单选按钮的值?请帮忙..

2 个答案:

答案 0 :(得分:0)

您必须使用mac获取document.getElementsByName数组并循环显示它们:

var allRadios = document.getElementsByName("mac");
var checkedItem; 
for(var i=0; i<allRadios.length; i++) {
     if (allRadios[i].checked) {
          checkedItem = allRadios[i];
          alert('Found checked radio button');
     }
 }

然后,您可以将checkedItem传递给getIframeContent功能。

修改

您可以使用checkedItem

在两个页面之间共享window变量
window.checkedItem = allRadios[i];

答案 1 :(得分:0)

长话短说。要访问iframe document,请使用.contentWindow.document,即:

document.getElementById('macList').contentWindow.document

示例代码:

<html>
  <head>
    <script type="text/javascript">
      function getIframeContent(){
         var myIFrame = document.getElementById('macList');
         var myIFDoc  = myIFrame.contentWindow.document;
         var myRadios = myIFDoc.getElementsByName("mac");

         var checkedItemValue = "";
         for(var i=0; i<myRadios.length; i++) {
            if (myRadios[i].checked) {
               checkedItemValue = myRadios[i].value;
            }
         }
         if (checkedItemValue) {
            alert(checkedItemValue);
         } else {alert('Select address');}
      }
    </script>
  </head>
<body>

  <iframe id="macList" src="..." 
      style="width:600px;height:160px">
  </iframe>

  <input type="submit" onclick="getIframeContent();">

</body>
</html>