javascript - 我有一个在 iframe 内带有单选按钮的表单,将文本插入到父文本区域。 "Undefined"来到 texarea 而不是单选按钮值

标签 javascript iframe radio-button onsubmit

如果我制作一个表单,并向其添加一个 ONSUBMIT,它会给出 UNDEFINED 作为父窗口“textarea”的答案,而不是所选的 RADIOBUTTON 中的值。我不想更改 javascript,因为它可以与具有 onclick 值的 javascript 一起正常工作,但是是否可以让 javascript 使用相同的脚本?或者我应该怎么做才能使这项工作成功?

这是我的工作示例:

index.html:

<html>
<head>
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1">
  <script type="text/javascript">
function hello(string){
// get the current text, add a newline if not blank, and append new
// text
var anchorText = document.getElementById('myAnchor').value;
if(anchorText !== "") anchorText += '\n';
anchorText += string;
document.getElementById('myAnchor').value=anchorText;
}
  </script>
  <title>joubadou</title>
</head>
<body>
<form>Cart<br>
  <br>
  <textarea rows="10" id="myAnchor"></textarea></form>
<iframe src="radiobuttontest.html" height="300"></iframe>
</body>
</html>

radiobuttontest.html:

<html>
<head>
  <title>Title</title>
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1">
</head>
<body>
<br>
<form id="myForm" action="" method="get"
 onsubmit="parent.hello()">If
you want a blue
car you can choose<br>
  <br>
  <input name="sex" value="Bensin" checked="checked"
 type="radio">Bensin<br>
  <input name="sex" value="Diesel" type="radio">Diesel<br>
  <br>
  <input value="add to cart"
 onclick="parent.hello('Blue car')" type="submit"></form>
<br>
</body>
</html>

如果你能帮助我,我会很高兴!

最佳答案

这就是用户点击添加到购物车时发生的情况:

  1. 输入的onclick触发,#anchorText的值为 更改为“Blue car”,并传递给 hello()

  2. onsubmit 从表单触发,#anchorText 的值为 更改为 undefined,因为 string 未传递。

要解决此问题,只需从表单中删除 onsubmit 属性,并传递单选按钮而不是字符串,例如:

将此 if 添加到 hello() 中:

function hello(string){
    if (typeof string === 'object') { // Checks if an object is passed instead of a string
        for (var n = 0; n < string.length; n++) { // Iterate through object
            if (string[n].checked) { // Check, if the current radio button is checked
                string = string[n].value; // Change the value of string to value of checked radio button
                break;
            }
        }
    }
    var anchorText = document.getElementById('myAnchor').value;
    :
}

并传递单选按钮,如下所示:

<input value="add to cart" onclick="parent.hello(document.getElementsByName('sex'));" ... />

请注意,当字符串作为参数传递时,您仍然可以使用 hello() 来处理字符串。

A live demo at jsFiddle 。这个 fiddle 只是一个示例,展示代码如何在单个文档中工作。

关于javascript - 我有一个在 iframe 内带有单选按钮的表单,将文本插入到父文本区域。 "Undefined"来到 texarea 而不是单选按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21510089/

相关文章:

javascript - 设置 iframe 的媒体类型?

HTML <frame> SRC 属性 - 使用 html 代码而不是 URL

php - 使用 php 和单选按钮更新数据

javascript - 创建元素后运行回调

iframe 中的 jQuery 在 IE 中不起作用

javascript - 已删除的文件仍在被访问

javascript - 根据单选按钮选择更改值和链接

html - 如何在一行中将单选按钮与标签、图例和字段集对齐

Javascript for 循环获取 key 并推送

javascript - 按内部文本 react native View 自动宽度