0

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!

jozpac
  • 84
  • 7

3 Answers3

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');
}
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