我有一个动态表,其中包含多个文本框。我需要文本框B最多输入6个数字,如果输入值小于或不等于6,则会提示错误。请帮助javascript新手
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="A" size="20" maxlength="6" required/>';
row.insertCell(1).innerHTML = '<input type="text" name="B" size="20" required/>';
row.insertCell(2).innerHTML = '<input type="text" name="C" size="20" required/>';
}
<input type="button" id="add" value="Add" onclick="Javascript:addRow()">
<table id="bod">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</table>
答案 0 :(得分:0)
手动创建input
并对其进行addEventListener
。像这样的东西。
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="A" size="20" maxlength="6" required/>';
var colB = row.insertCell(1);
var inp = document.createElement('input');
inp.type = 'text';
inp.name = 'B';
inp.size = 20;
inp.required = true;
colB.appendChild(inp);
inp.addEventListener('change', function() {
if (this.value.length !== 6) {
alert('wrong value');
this.focus();
}
});
row.insertCell(2).innerHTML = '<input type="text" name="C" size="20" required/>';
}
<input type="button" id="add" value="Add" onclick="addRow()">
<table id="bod">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</table>