簡體   English   中英

我該如何使用 <form> 標簽將數據發送到javascript函數?

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

我正在測試,並嘗試制作一個小的表格,以便當用戶輸入他們的姓名時,它將使用該姓名並將其顯示在屏幕上。

<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>

這是js文件

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

我知道我可以在一個HTML文件中執行此操作,但是我想嘗試將js和HTML分開。 任何幫助表示贊賞。

您無需將數據發送到JavaScript函數,但是JavaScript函數可以檢索表單數據。

例如,可以使用其value屬性來檢索類型text輸入:

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

我知道我可以在一個HTML文件中執行此操作,但是我想嘗試將js和HTML分開。

好一步。 實際上,從內聯腳本或使用<script src=...元素包含的腳本中檢索表單數據或操作文檔方面,沒有任何實際差異。 主要區別是不會緩存HTML文檔中嵌入的腳本,而將緩存作為單獨文件包含的腳本(顯然,如果我們談論良好的關注點分離,還有其他原因!)。

在文本框上使用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 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