I created the field on form html with press enter instead of tab, i want to make automatic create new same form when its enter in last field form
my problem : the form automatic created starting with the second field, and the form always makes a multiple of 2 forms
expetation : created new same form once the user presses enter in the last field, and its just always 1 form only so on, and the select form follow the next new field form too.
Script
var display = document.getElementById("area")
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e;
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i ) {
var q = (i == ele.length - 1) ? 0 : i 1;
if (obj == ele[i]) {
ele[q].focus();
break
}
display.insertAdjacentHTML('beforeend',
`<form method="" action="">
<table>
<td>1<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>2<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>3<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>4<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>5<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>6<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>7<br><input type="text" onkeypress="return tabE(this,event)"></td>
</table>
</form>`);
}
return false;
}
}
<body onkeydown="javascript:if(window.event.keyCode == 13) window.event.keyCode = 9;">
<div id="area">
<form method="" action="">
<table>
<td>1<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>2<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>3<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>4<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>5<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>6<br><input type="text" onkeypress="return tabE(this,event)"></td>
<td>7<br><input type="text" onkeypress="return tabE(this,event)"></td>
</table>
</form>
</div>
</body>
CodePudding user response:
Perhaps this will work for you?
I fixed the HTML too
const display = document.getElementById("area")
const table = document.getElementById("t1")
table.addEventListener("keypress", function(e) {
if (e.code == "Enter") {
const tgt = e.target;
if (e.target.classList.contains("last")) {
const row = table.querySelector("tr").cloneNode(true);
row.querySelectorAll("input").forEach(inp => inp.value="")
table.appendChild(row);
row.querySelector("input").focus()
}
else {
tgt.closest('td').nextElementSibling.querySelector('input').focus()
}
}
});
<div id="area">
<form method="" action="">
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="t1">
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text" ></td>
</tr>
</tbody>
</table>
</form>
</div>