I am trying to handle Backspace key press of a user. I have 2 handlers bound to one input element. Since it is not possible to detect key press in the onChange event handler, I have to do it in the onKeyDown. I want to stop the propagation of onChange event when backspace is pressed (and handled in the onKeyDown event handler). Any ideas how to achieve this? Thank you!
Asked
Active
Viewed 533 times
0
-
`event.preventDefault()` and `event.stopPropagation()`? – Jonas Wilms Mar 22 '21 at 14:53
-
this doesn't stop the onChange event. – jozpac Mar 22 '21 at 14:54
-
Ah, now I understand. No you cannot do that – Jonas Wilms Mar 22 '21 at 14:54
-
can you add a concrete [mre]? – Jonas Wilms Mar 22 '21 at 14:55
-
Is it possible to achieve it in a totally different way? Like using state. But I don't believe that since state setting is asynchronous.. – jozpac Mar 22 '21 at 14:55
-
First, handle the onKeyDown event, if the key is backspace, stop onChange event, otherwise let it continue... Also I want to get the keycode to the onChange event so I can use it in a condition. – jozpac Mar 22 '21 at 14:57
3 Answers
1
If you has Select Option: When you click on select tag, onChange and onClick event is fired. I solved this by creating a onClick handler side onChange handle and then calling e.stopPropogation().
<select onClick ="St(event)" onChange ="Tc(event)" >
<option>Case</option>
</select>
St(event) {
event.stopPropagation();
console.log('Next');
}
Tc(event) {
event.stopPropagation();
console.log('Nex here');
}

Shavleg Kakulia
- 19
- 3
1
If you are trying to prevent backspace, you can store the input's value in state and pass it as prop to the input, and in onChange of the input compare e.target.value with the value stored in state and update the state variable
const [value, setValue] = useState("");
const checkValue = (newValue) => {
if (value.length < newValue.length) setValue(newValue);
};
<input value={value} onChange={(e) => checkValue(e.target.value)} />

Kaushik
- 921
- 10
- 18
0
As I thought it was possible to do it in this way. You can create some auxilliary variable/property and set the keyCode to it in the onKeyDown handler. Then you are able to use this conditionally wherever you want (for me, in the onChange event handler).

jozpac
- 84
- 7