JavaScript - DOM 表單



DOM 表單

HTML DOM 文件的表單用於獲取使用者的資料。

在 JavaScript 中,您可以使用 'document' 物件的'forms' 集合來訪問 HTML 文件中的所有 <form> 元素。

您可以訪問特定表單的所有表單元素並對其進行操作。使用 JavaScript,您可以驗證表單值、處理表單資料提交等。

語法

請遵循以下語法來使用 'forms' 集合操作 DOM 的表單。

document.forms;

這裡,'forms' 是 'document' 物件的一個屬性。

'forms' 集合的屬性

屬性 描述
length 它表示 HTML 文件中 <form> 元素的數量。

'forms' 集合的方法

方法 描述
[index] 從 HTML 表單集合的基於 0 的索引中獲取特定的 <form> 元素。
item(index) 從 HTML 表單集合的基於 0 的索引中獲取特定的 <form> 元素。
namedItem(id) 獲取具有特定 id 的 <form> 元素。

返回值

document.forms 返回 HTML 文件中所有表單的集合,其順序與它們在 HTML 文件中的順序相同。

示例:查詢 HTML 文件中 <form> 元素的總數

在下面的程式碼中,我們使用 'forms' 集合的 'length' 屬性來查詢 HTML 文件中存在的表單數量。

<html>
<body>
  <form>
    <input type = "text" name = "first" id = "first" value = "First Name">
  </form>
  <form>
    <input type = "text" name = "second" id = "second" value = "Last Name">
  </form>
  <form>
    <input type = "text" name = "third" id = "third" value = "Contact">
  </form>
  <div id = "output">Total number of forms in the HTML document is: </div>
  <script>
    document.getElementById('output').innerHTML += document.forms.length;
  </script>
</body>
</html>

示例:獲取所有 <form> 元素的 id

在下面的程式碼中,我們使用其索引訪問每個表單,並使用 'id' 屬性獲取特定表單的 id。

<html>
<body>
<form id = "form1">
  <label for = "first"> Fruit Name: </label>
  <input type = "text" name = "first" id = "first">
</form>
<form id = "form2">
  <label for = "second"> Price: </label>
  <input type = "text" name = "second" id = "second">
</form>
<form id = "form3">
  <label for = "third"> Color: </label>
  <input type = "text" name = "third" id = "third">
</form>
<div id = "output"> </div>
<script>
  document.getElementById('output').innerHTML = 
  "Id of the first form is: " + document.forms[0].id + "<br>" +
  "Id of the second form is: " + document.forms[1].id + "<br>" +
  "Id of the third form is: " + document.forms[2].id;
</script>
</body>
</html>

示例:使用其 id 和 namedItem() 方法獲取特定表單

在下面的程式碼中,我們使用 namedItem() 方法並以 'forms' 集合作為參考來獲取具有特定 id 的表單。

<html>
<body>
<form id = "form1">
    <label for = "first"> First Name </label>
    <input type = "text" name = "first" id = "first">
  </form>
  <form id = "form2">
    <label for = "second"> Last Name </label>
    <input type = "text" name = "second" id = "second">
  </form>
<div id = "output">The innerHTML of the form element having id equal to form2 is: </div>
  <script>
    const output = document.getElementById('output');
    output.innerHTML += document.forms.namedItem('form2').innerHTML;
  </script>
</body>
</html>

JavaScript 表單提交

在 JavaScript 中,您可以使用 'submit' 輸入型別提交表單,並執行特定函式以使用 onsubmit() 事件處理程式處理表單資料。

示例

在下面的程式碼中,表單獲取使用者的姓和名。然後,當用戶單擊提交輸入時,它會呼叫 submitForm() 函式。

在 submitForm() 函式中,我們使用 preventDefault() 方法來防止在不提交表單的情況下執行函式。

之後,我們使用 'forms' 集合訪問表單及其輸入欄位的值。

最後,我們在輸出中列印輸入值。

<html>
<body>
<form onsubmit = "submitForm(event)" id = "nameform">
  <p><label>First Name: </label><input type = "text" name = "firstname"></p>
  <p><label>Last Name: </label><input type = "text" name = "lastname"></p>
  <p><input type = "submit"></p>
</form>
<div id = "output"> </div>
<script>
  function submitForm(e) {
    e.preventDefault(); 
    const output = document.getElementById('output');
    const firstname = document.forms['nameform']['firstname'].value;
    const lastname = document.forms['nameform']['lastname'].value; 
    output.innerHTML = "First Name: " + firstname + ", Last Name: " + lastname;
  }
</script>
</body>
</html>

JavaScript 表單驗證

在 JavaScript 中,您還可以驗證表單以確保使用者已填寫必填輸入。您可以在表單提交時呼叫的函式中執行驗證檢查。

此外,如果表單不滿足特定條件,您還可以顯示錯誤訊息。

示例

在下面的程式碼中,當用戶提交表單時,我們檢查姓和名的長度是否小於 3。如果姓或名的長度小於 3,我們顯示錯誤訊息。

<html>
<body>
<form onsubmit = "submitForm(event)" id = "nameform">
  <p>First Name: <input type = "text" name = "firstname"> </p>
  <p>Last Name: <input type = "text" name = "lastname"> </p>
  <p><input type = "submit"></p>
</form>
<div id = "output"> </div>
<script> 
  function submitForm(e) {
    e.preventDefault();
    const output = document.getElementById('output');
    const firstname = document.forms['nameform']['firstname'].value;
    const lastname = document.forms['nameform']['lastname'].value;
    if (firstname.length < 3 || lastname.length < 3) {
      output.innerHTML += "The length of the first name or last name should be greater than 3. <br>";
    } else {
      output.innerHTML = "First Name: " + firstname + ", Last Name: " + lastname;
    }
  }
</script>
</body>
</html>

JavaScript 表單資料驗證

還需要驗證輸入資料。

有時,您可能希望使用者傳遞數字資料,但他們卻錯誤地傳遞了字串資料。在這種情況下,開發人員需要驗證資料並顯示錯誤訊息。

您可以客戶端或伺服器端驗證資料。最佳實踐是在客戶端驗證資料並將純資料傳送到伺服器。

示例

在下面的程式碼中,我們建立了一個輸入欄位,用於從使用者那裡獲取電子郵件。當用戶提交表單時,我們使用正則表示式和 test() 方法來檢查他們是否在輸入中傳遞了有效的電子郵件地址。

<html>
<body>
  <form onsubmit = "submitForm(event)" id = "emailform">
    <p>Email: <input type = "email" name = "email"> </p>
    <p><input type = "submit"></p>
  </form>
  <div id = "output"> </div>
  <script>
    function submitForm(e) {
      e.preventDefault();

      const email = document.forms['emailform']['email'].value;
      //Validate email using regex
      const emailRegex = /^[a-z0-9]+@[a-z]+\.[a-z]{2,3}$/;
      if (emailRegex.test(email)) {
        document.getElementById('output').innerHTML = "Email is valid!";
      } else {
        document.getElementById('output').innerHTML = "Email is not valid!";
      }
    }
  </script>
</body>
</html>

使用 HTML 約束進行表單驗證

(自動錶單驗證)

在 HTML5 中,引入了一些約束來驗證表單。您可以將這些約束用作 HTML 元素的屬性,如果輸入不匹配約束,則它會阻止表單提交。

下表包含約束及其描述。

約束 描述
disabled 停用輸入元素。
max 指定輸入元素的最大值。
min 指定輸入元素的最小值。
pattern 指定輸入元素的特定模式。
required 將輸入元素指定為必填欄位。
type 指定輸入元素的型別。

語法

按照以下語法將上述約束作為屬性新增到 <input> 元素。

<input attr=value >

示例:使用 required 屬性

在下面的程式碼中,我們將 'required' 屬性與輸入元素一起使用。當您在不輸入輸入欄位中的數字的情況下提交表單時,它將顯示預設的錯誤訊息。

<html>
<body>
  <form onsubmit = "submitForm(event)" id = "form">
    <p>Number: <input type = "number" name = "num" required> </p>
    <p><input type = "submit"></p>
  </form>
  <div id = "output"> </div>
  <script>
    function submitForm(e) {
      e.preventDefault();
      const num = document.forms['form']['num'].value;
      document.getElementById('output').innerHTML += "The submitted numeric value is: " + num + "<br>";
    }
  </script>
</body>
</html>

HTML 表單驗證約束提供了有限的功能。因此,您可以編寫自定義 JavaScript 函式來驗證表單。

您也可以使用 CSS 選擇器來驗證表單。

廣告