I have an input field. I want React to check if a tab has been pressed in this field. If so, then process the contents of that field (e.g. ajax call).
getInitialState: function() {
return { name: "" };
},
handleChangeName: function(e) {
this.setState({name: e.target.value});
},
handleKeyUp: function(e) {
if (e.keyCode == 9) {
e.preventDefault();
alert("Execute ajax call after tab pressed");
}
},
<input type="text" value={this.state.name} onChange={this.handleChangeName}
onKeyDown={this.handleKeyUp} />
Problem:
Tab keypress is intercepted and subsequent code executed but the tab character is inserted into the input text field. How do I prevent this from happening?
I have tried various combinations of preventDefault
, stopPropagation
, stopImmediatePropagation
. I can get a result of no further chars being inserted into the input text field, but then no subsequent code is executed.
What am I missing?
The events onKeyUp or onKeyPress won't be called when 'Tab' is pressed because it triggers a onBlur before, you need to catch it with onKeyDown. You can try to use the event key instead of keyCode, as the example above.
function:
handleKeyDown: function(e) {
if (e.key === "Tab") {
e.preventDefault();
alert("Execute ajax call after tab pressed");
}
}
input:
<input type="text" onKeyDown={this.handleKeyDown} />
I hope it helps ;).
I think it's somehow connected with the fact that you pass both onChange and onKeyDown handlers.
I think you have following options:
<input type="text" value={this.state.name} onKeyDown={this.handleKeyUp} onChange={this.handleChangeName} />
handleKeyPress(e) {
if (e.keyCode === 9) {
e.preventDefault();
return alert('hey ho lets go');
}
this.setState({name: e.target.value});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With