[英]How to Check the Value of a Text Input If There Are Multiple Inputs with the Same Name?
我有幾個文本輸入,一旦我點擊提交,我的 PHP 腳本就會收到數組 $_POST['length']。
<form method="POST" action="myscript.php">
<input type="text" name="length[]" value="" onInput='checkinput();'>
<input type="text" name="length[]" value="" onInput='checkinput();'>
<input type="text" name="length[]" value="" onInput='checkinput();'>
<input type="submit" value="Submit">
</form>
我想使用 Javascript function 來確保用戶在每個文本框中只輸入數字。 每次在其中一個框中輸入內容時,都會執行 checkinput() function。 如何讓 function 從用戶輸入的右側框中獲取值,以便檢查該值?
編輯:我想允許數字和小數。
HTML5 具有您需要的僅數字驗證。 只需在輸入字段中輸入type="number"
,而不是輸入文本。
關於問題的 JS 部分 - 當您在輸入框中輸入內容時,將調用checkInput()
。
在其中,您將獲得一個事件作為參數,如下所示:
function checkInput(e) {}
您可以使用this
關鍵字或事件 object 來獲取輸入的值。
function checkInput(e) {
const value = e.target.value;
// check if value is a number
// etc.
}
更新:
也許嘗試數據屬性。 您的 HTML 將如下所示:
<form id="inputform">
<input type="text" name="length[]" value="" data-number="1" />
<input type="text" name="length[]" value="" data-number="2" />
<input type="text" name="length[]" value="" data-number="3" />
<input type="submit" value="Submit" />
</form>
JavaScript 像這樣:
var formElem = document.querySelector("#inputform");
formElem.addEventListener("input", checkInput);
function checkInput(e) {
console.log(e.target.dataset.number);
console.log(e.target.value);
}
根據修改的輸入,這將為您提供 1、2 或 3。 您還可以在e.target.value
中獲取用戶輸入的值
您可以將this
作為checkInput
function 的參數傳遞
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.