简体   繁体   English

我该如何使用 <form> 标签将数据发送到javascript函数?

[英]How do I use the <form> tag to send data to a javascript function?

I was testing and trying to make an little form that when the user entered their name, it would take that name and display it on to the screen. 我正在测试,并尝试制作一个小的表格,以便当用户输入他们的姓名时,它将使用该姓名并将其显示在屏幕上。

<html>
<head>
    <center><h1>Test-Page</h1></center>
</head>
<body>
    <div class="someRandomStuff">
    <h2 id="testingID">What is your first name?</h2>
    <form name="input" action="login.js" method="post">
        Name: <input type="text" name="userID"/>
        <input type="submit" value="Submit"/>
    </form>
    </div>
</body>

Here is the js file 这是js文件

function displaySystem(name) {
    document.getElementById("testingID").innerHTML("Ah, hello there" + name)
}

I know that I could probably do this in one HTML file, however I want to try and make the js and HTML separate. 我知道我可以在一个HTML文件中执行此操作,但是我想尝试将js和HTML分开。 ANY help is appreciated. 任何帮助表示赞赏。

You don't send data to a JavaScript function, but a JavaScript function can retrieve form data. 您无需将数据发送到JavaScript函数,但是JavaScript函数可以检索表单数据。

For example, and input of type text can be retrieved using its value property: 例如,可以使用其value属性来检索类型text输入:

var input = document.getElementById("userID");
var value = input.value;

I know that I could probably do this in one HTML file, however I want to try and make the js and HTML separate. 我知道我可以在一个HTML文件中执行此操作,但是我想尝试将js和HTML分开。

Nice step. 好一步。 In fact, there's no practical difference in terms of retrieving form data or manipulating the document from an inline script or a script that's included using a <script src=... element. 实际上,从内联脚本或使用<script src=...元素包含的脚本中检索表单数据或操作文档方面,没有任何实际差异。 The main difference is a script embedded in the HTML document won't be cached, while a one included as a separate file will be cached (obviously, there're other reasons if we talk about good separation of concerns!). 主要区别是不会缓存HTML文档中嵌入的脚本,而将缓存作为单独文件包含的脚本(显然,如果我们谈论良好的关注点分离,还有其他原因!)。

use onkeypress event on textbox and pass this to display that value and use that parameter in function to display it 在文本框上使用onkeypress事件,并将其传递给该值以显示该值,并在函数中使用该参数显示该值

   <div class="someRandomStuff">
        <h2 id="testingID">What is your first name?</h2>
        <form name="input" action="login.js" method="post">
            Name: <input type="text" name="userID" onkeypress="displaySystem(this)"/>
            <input type="submit" value="Submit"/>
        </form>
        </div>

//javascript function // javascript函数

function displaySystem(name) {
    document.getElementById("testingID").innerHTML("Ah, hello there" + name.value)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM