As I can tell it’s not possible to just assign delete keycode to another key, so I tried to recreate its functionality, but I can’t figure out how to do it properly.
I tried to do it with slice, and it actually does what it should for the first time, but then any key I press triggers delete.
window.addEventListener("keydown", function(e) {
let formuleInput = $(".mat-input-element");
if ($(formuleInput).is(':focus')) {
formuleInput[0].addEventListener('keyup', function(f) {
let caretPos = f.target.selectionStart;
console.log(caretPos);
let fInput = formuleInput[0].value;
if (e.keyCode === 32 && $(formuleInput).is(':focus')) {
e.preventDefault();
fInput = fInput.slice(0, caretPos) + fInput.slice(caretPos + 1);
formuleInput[0].value = fInput;
}
})
}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="mat-input-element">
2
Answers
This should work, but you don’t need jQuery to do it. Attach the event to the input instead of the window. That way you don’t have to capture every single keypress event and filter it based on the input.
This uses the keydown event to remove the default functionality of adding a space on the key 32’s default behavior and then uses the substring argument to remove the last typed character from the input value.
To make the spacebar act the same as the delete key does, for both selected and unselected text: