在 JavaScript 中設定 Textarea 值
本文展示瞭如何使用純 JavaScript 設定 <textarea> 值。
什麼是 HTML 中的 <textarea>
    
當你希望允許使用者輸入大量自由文字作為對評估或反饋模組的評論時,HTML 元素 <textarea> 表示有用的多行文字編輯控制元件。
<textarea> 提供了幾個特性。
id屬性允許<textarea>與<label>元素關聯以實現可訪問性目的。name屬性,用於指定在提交表單時將傳送到伺服器的關聯資料項的名稱。row和column屬性允許你指定<textarea>應該佔用的確切大小。設定這些首選項是保持一致性的好主意,因為瀏覽器預設值可能會有所不同。- 在開始和結束標籤之間插入預設內容。 
<textarea>不支援value屬性。 
<textarea> 元素還接受幾個通用屬性來形成 <input>,例如 autocomplete、autofocus、disabled、wildcard、read-only 和 required .
在 JavaScript 中設定 <textarea> 值
getElementById() 是 JavaScript 提供的整合文件方法,它返回 id 與指定 id 匹配的元素物件。
語法:
getElementById($id)
$id 是一個強制引數,它指定必須匹配的 HTML 屬性的 id。如果找到對應的元素,則返回對應的 DOM 元素物件;否則,它返回 null。
現在,讓我們使用 getElementById() 提取文字區域節點元素。
<textarea id="address" name="address">Please Fill the address</textarea>
<button id="btn" onclick="clearValue()">Click to clear</button>
function clearValue() {
  document.getElementById('address').value = '';
}
在上面的程式碼中,我們使用 getElementById 來查詢 DOM 中存在的文字區域元素。單擊 clear 按鈕後,找到文字區域節點。
使用所需的值更新 value 屬性。
現在讓我們執行上面的程式碼並點選按鈕來移除文字區域的值。它將刪除文字區域的值,看起來像這樣。
<textarea> 之前:

<textarea> 之後:

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn