如何在输入字段中自动生成数字?

时间:2019-03-17 14:38:39

标签: javascript jquery html

我正在创建带有自动编号ID列的表。我希望我的输入文本字段能够自动生成一个ID号(当用户开始在名称输入字段中键入内容时)。

如何在输入字段中自动生成数字?

2 个答案:

答案 0 :(得分:0)

您可以使用下面的代码。它的作用是每次单击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>

答案 1 :(得分:0)

如果您有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>