Reputation: 103
I want the user to enter his firstName but no spaces in between. I tried to use this code but it doesn't serve the purpose .
<TextField
required
id="name"
label="First Name"
name="firstName"
className={classes.textField}
margin="normal"
defaultValue={firstName}
onkeypress="return AvoidSpace(event)"
/>
Here is the function that we are using .
function AvoidSpace(event) {
var k = event ? event.which : window.event.keyCode;
if (k == 32) return false;
}
Here is the link to the code . jsfiddle
It seems as if TextField doesn't accept onkeypress. I tried but it failed. https://codesandbox.io/s/1o0mqk2mm3
Upvotes: 3
Views: 10980
Reputation: 515
You should pass onChange
to TextField
and use the state to handle the change:
onChange = (e) => {
this.setState({firstName: e.target.value.trim()})
}
<TextField
required
id="name"
label="First Name"
name="firstName"
className={classes.textField}
margin="normal"
defaultValue={firstName}
onChange={this.onChange}
/>
Upvotes: 1