[英]How to auto generate number in an input field?
我正在創建帶有自動編號ID列的表。 我希望能夠讓我的輸入文本字段自動生成一個ID號(當用戶開始在名稱輸入字段中鍵入內容時)。
如何在輸入字段中自動生成數字?
您可以使用下面的代碼。 它的作用是每次您單擊“ insert
按鈕時,都會在項目的ID上添加一個數字(文本字段旁邊的數字)。
此代碼使用document.getElementById()
來修改所有元素,並使用變量num
來增加id值。 將項目添加到列表中的部分是可選的-我只是添加了它以使其看起來更逼真。
var num = 1; var input = document.getElementById('item'); var p = document.getElementById('number'); var list = document.getElementById('list'); var button = document.getElementById('insert'); button.addEventListener('click', function() { num++; p.innerHTML = num; list.innerHTML += "<li>" + input.value + "</li>"; });
#item { display: inline; } #number { display: inline; margin-right: 10px; }
<p id='number'>1</p> <input type='text' id='item' /> <button id='insert'>Insert</button> <ul id='list'> </ul>
如果您有HTML表格,則可以響應所有編輯,偵聽input
事件並決定是否填寫唯一編號(或清除它)。
這是您可以調用的通用函數,該函數將應具有此功能的表格元素以及應獲取這些ID值的列號作為參數。
例:
function autoId(table, colNo) { table.addEventListener("input", function(e) { const tr = e.target.closest("tr"); const idInput = tr.cells[colNo].querySelector("input"); for (const input of tr.querySelectorAll("input")) { hasData = input.value.trim() !== "" && input !== idInput; if (hasData) break; } if (hasData && idInput.value.trim() === "") { idInput.value = (Math.max(...Array.from( table.querySelectorAll("td:nth-child(" + (colNo+1) + ") input"), input => +input.value ).filter(v => !isNaN(v))) || 0) + 1; } else if (!hasData && idInput.value.trim() !== "") { idInput.value = ""; } }); } const table = document.querySelector("table"); // Call the function passing it the table and the column that has the ID -- that's all autoId(table, 0); // Let's give user the possibility to add rows, using the first data row as template document.querySelector("#btnAddRow").addEventListener("click", () => { table.insertAdjacentHTML("beforeend", table.rows[1].innerHTML); });
<table> <tr><th>ID</th><th>Name</th></tr> <tr><td><input size="2"></td><td><input></td></tr> </table> <button id="btnAddRow">Add row</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.