I have a contenteditable element what I update/filter with javascript. After updating the textcontent the but the caret always goes back to the beginning. A want to make to work like the input element. I set up a demo:
- test1 - contenteditable element
- test2 - input element
In this example I have a function what enable to insert only numbers, if you insert other characters nothing will show.
After entering some numbers to the contenteditable and inserting a NOT number, then the cursor (caret) goes to the start. In case of input element the cursor goes to the end.
How to achieve that, to remain the cursor to the position where it was? (pure javascript)
function onlyNumber(element) {
const invalidChars = /\D/g;
ob = element.target;
if (element.target.nodeName == "INPUT") {
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
} else if (element.target.nodeName == "TD") {
if (invalidChars.test(ob.textContent)) {
ob.textContent = ob.textContent.replace(invalidChars, "");
}
}
}
document.getElementById("test1").addEventListener("input", function(event) {
onlyNumber(event);
})
document.getElementById("test2").addEventListener("input", function(event) {
onlyNumber(event);
})
#test1 {
border: 1px solid gray;
padding: 5px;
width: 100px;
}
#test2 {
margin-top: 15px;
}
<table class="table">
<tbody>
<tr>
<td id="test1" contenteditable="true"></td>
</tr>
</tbody>
</table>
<input id="test2" />