簡體   English   中英

如何正確顯示表單 HTML 輸入

[英]How do I properly display form HTML input

我的代碼沒有按我的預期工作,我不知道如何修復它。 所以,每當人們在框中輸入“你好”,然后按下提交,段落帽子說 hi 應該顯示“好工作”,但事實並非如此。

 <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <textarea id="thesearchh" style="resize: none;"></textarea> <button onclick="submitSearch()">Submit</button> <p id="searchResult">hi</p> <script> function submitSearch() { if(document.getElementById('thesearchh').includes('hello') == true) { document.getElementById('searchResult').innerHTML = 'good job'; } } </script> </body> </html>

您應該使用document.getElementById(inputId).value檢查輸入值,而不是使用includes方法。 include 方法適用於數組和字符串,但不適用於 DOM 元素。

 <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <textarea id="thesearchh" style="resize: none;"></textarea> <button onclick="submitSearch()">Submit</button> <p id="searchResult">hi</p> <script> function submitSearch() { if(document.getElementById('thesearchh').value === "hello") { document.getElementById('searchResult').innerHTML = 'good job'; } } </script> </body> </html>

  • 停止使用內聯屬性,例如:CSS style和 JS on*處理程序。 CSS 和 JS 應該在各自的標簽或文件中。
  • 使用Element.addEventListener()而不是 onclick 屬性處理程序
  • 使用InputElement.value獲取 :input 的(在您的情況下為<textarea> )值。
  • 使用===將其與所需的"hello"字符串進行比較
  • PS:你確定你需要一個<textarea>而不是<input type="text">嗎?
  • 此外,您可能希望在比較之前使用 String.prototype.trim() 從用戶輸入字符串中刪除空格。 這取決於你。

 <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> #search { resize: none; } </style> </head> <body> <textarea id="thesearchh"></textarea> <button type="button" id="thesubmitt">Submit</button> <p id="searchResult">hi</p> <script> // DOM Utility functions: const el = (sel, par) => (par??document).querySelector(sel); // Task: Match value "hello": const elSearch = el("#thesearchh"); const elSubmit = el("#thesubmitt"); const elResult = el("#searchResult"); const submitSearch = () => { const userInput = elSearch.value; if (userInput === "hello") { elResult.textContent = 'good job'; } }; elSubmit.addEventListener("click", submitSearch); </script> </body> </html>

剛剛在您的代碼中添加了.value

 <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <textarea id="thesearchh" style="resize: none;"></textarea> <button onclick="submitSearch()">Submit</button> <p id="searchResult">hi</p> <script> function submitSearch() { if(document.getElementById('thesearchh').value.includes('hello') == true) { document.getElementById('searchResult').innerHTML = 'good job'; } } </script> </body> </html>

在這里您可以看到 iam added .value 行

if(document.getElementById('thesearchh').value.includes('hello') == true){}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM