簡體   English   中英

使用 JavaScript 檢查用戶輸入

[英]Using JavaScript to check for user-input

我正在通過我的網絡客戶端向我的服務器提交一個帶有輸入文本的表單。 我想要做的是檢查用戶是否在通過點擊提交按鈕發送表單之前將文本傳遞到輸入字段中。

到目前為止我嘗試過的:

 var form = document.getElementById("id"); document.getElementById("id").addEventListener("click", function() { var input = document.getElementById("content").value; if (input == "") { alert("write something in the textfield"); } else { form.submit(); } });
 <form action="" method="post" id="id"> <input type="text" name="name" id="content"> <button type="submit" id="submit-id">submit text</button> </form>

關於如何做到這一點的任何好提示?

您希望在提交事件上防止默認

 document.getElementById("id").addEventListener("submit", function(e) { const input = document.getElementById("content").value; if (input.trim() === "") { alert("write something in the textfield"); e.preventDefault() } });
 <form action="" method="post" id="id"> <input type="text" name="name" id="content"> <button type="submit" id="submit-id">submit text</button> </form>

或者,只需添加 required 屬性 - 不需要腳本:

 <form action="" method="post" id="id"> <input type="text" name="name" id="content" required> <button type="submit" id="submit-id">submit text</button> </form>

我正在通過我的網絡客戶端向我的服務器提交一個帶有輸入文本的表單。 我想要做的是檢查用戶是否在通過點擊提交按鈕發送表單之前將文本傳遞到輸入字段中。

到目前為止我嘗試過的:

 var form = document.getElementById("id"); document.getElementById("id").addEventListener("click", function() { var input = document.getElementById("content").value; if (input == "") { alert("write something in the textfield"); } else { form.submit(); } });
 <form action="" method="post" id="id"> <input type="text" name="name" id="content"> <button type="submit" id="submit-id">submit text</button> </form>

關於如何做到這一點的任何好提示?

您可以改用簡單的代碼片段:

 <form action="" method="post" id="id"> <input type="text" name="name" id="content" required> <button type="submit" id="submit-id">submit text</button> </form>

 function submitIt(e) { var formData = new FormData(e); var object = {}; formData.forEach(function(value, key) { object[key] = value; }); if (object.name == "") { alert("null"); } else { alert("ok"); return true; } return false; }
 <form onsubmit="return submitIt(this)"> <input type="text" name="name"> <button>submit text</button> </form>

暫無
暫無

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

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