'How to get the TextField value when enter key is pressed in React?
I want to pass TextField
values when user press enter key from keyboard. In onChange()
event, I am getting the value of the textbox
, but How to get this value when enter
key is pressed ?
Code:
import TextField from 'material-ui/TextField';
class CartridgeShell extends Component {
constructor(props) {
super(props);
this.state = {value:''}
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({ value: e.target.value });
}
render(){
return(
<TextField
hintText="First Name"
floatingLabelText="First Name*"
value={this.state.value}
onChange={this.handleChange}
fullWidth={true} />
)
}
}
Solution 1:[1]
Adding onKeyPress will work onChange in Text Field.
<TextField
onKeyPress={(ev) => {
console.log(`Pressed keyCode ${ev.key}`);
if (ev.key === 'Enter') {
// Do code here
ev.preventDefault();
}
}}
/>
Solution 2:[2]
You can use e.target.value
to get the current value of the input
element if you're using uncontrolled mode.
<TextField
onKeyPress={(e) => {
if (e.key === 'Enter') {
alert(e.target.value);
}
}}
/>
Live Demo
Solution 3:[3]
<input onKeyPress={onKeyPress}/>
const onKeyPress = (e: any) => { if (e.which == 13) { // your function }};
Solution 4:[4]
html
<input id="something" onkeyup="key_up(this)" type="text">
script
function key_up(e){
var enterKey = 13; //Key Code for Enter Key
if (e.which == enterKey){
//Do you work here
}
}
Next time, Please try providing some code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | brooksrelyt |
Solution 2 | |
Solution 3 | Skender Ademi |
Solution 4 | manish |