如何使用 javascript 在新窗口中的 html 字段中显示值

How do I display value in a html field in a new window with javascript?

本文关键字:html 字段 显示 窗口 javascript 何使用 新窗口      更新时间:2023-09-26

我基本上是在尝试验证输入字段,打开一个新窗口并在新窗口中显示输入字段的内容。我已经打开了新窗口,但不会将文本发布到"displayText"字段。

.html:

<head>
    <title>Q3</title>
    <script type ="text/javascript" src="functions.js"></script>
</head>
<body>
  <!-- Form -->
  <form name="f3">
    Text: <input type="text" id="tb5" name="tb5"><br/>
    <button onclick="validateQ3()" Type="button" id="b1" name="b1">Submit</button>
  </form>

JavaScript:

function validateQ3() {
    // Get value from text box
    var a = document.getElementById("tb5").value;
        // Check that textbox is neither empty nor contains null
    if (a == null || a == "")
    {
        // if error, display error
        alert("Textbox cannot be empty");
        return false;
    }
    // Check text field >= 5
    if (a.length < 5)
    {
        alert("Field must be longer than 5 characters");
        return false;
    }
    else 
    {
        // Call newWindow() function
        newWindow(a);
    }
}//validateQ3()
function newWindow(a) {
    // Open new window
    var newWindow = window.open("", "mypopup", "height=300 , width=300");
    newWindow.document.write("<p id='displayText'></p>");
    if (window.focus)
    {
        newWindow.focus();
    }
    var tmp = newWindow.document;
    tmp.write('<html><head><title>mypopup</title></head>');
    tmp.write('<body><p id="displayText"></p></body></html>');
    document.getElementById("displayText").innerHTML = a;
    tmp.close();
}

任何帮助表示赞赏

您正在尝试在当前窗口而不是新窗口上设置元素的 innerHTML,第一个窗口中不存在 displayText,请将文档更改为:

 tmp.getElementById("displayText").innerHTML = a;