I have an input
:
<input type="text" value={this.state.current} onChange={this.handleChange.bind(this)} />
handleChange()
method:
handleChange(e) {
let val = parseInt(e.target.value);
if (val) {
this.set(val);
}
}
and set()
method (simple set number between 1 and 5 to the state):
set(val = 1) {
if (val < 1) {
val = 1;
}
if (val > 5) {
val = 5;
}
this.setState({ current: val });
}
My problem is: when i want to change value in input, i can't delete number from it. I think it is auto filled from state imediatly after I delete number. Where is the problem in my code?
exmaple on jsFiddle: /
I have an input
:
<input type="text" value={this.state.current} onChange={this.handleChange.bind(this)} />
handleChange()
method:
handleChange(e) {
let val = parseInt(e.target.value);
if (val) {
this.set(val);
}
}
and set()
method (simple set number between 1 and 5 to the state):
set(val = 1) {
if (val < 1) {
val = 1;
}
if (val > 5) {
val = 5;
}
this.setState({ current: val });
}
My problem is: when i want to change value in input, i can't delete number from it. I think it is auto filled from state imediatly after I delete number. Where is the problem in my code?
exmaple on jsFiddle: https://jsfiddle/4sc3p2ny/
Share Improve this question asked Jul 28, 2016 at 13:00 mwlmwl 1,48814 silver badges19 bronze badges 2-
set(val = 1)
is only for init. Even if i remove it (set(val)
) i still can't delete numbers from input. – mwl Commented Jul 28, 2016 at 13:06 -
If you will remove set(val) it will not allow you to change as it shows value mapped to
current
, which will not change if you will removeset(val)
– Pardeep Dhingra Commented Jul 28, 2016 at 13:10
2 Answers
Reset to default 6When you are trying pletely remove value from input, e.target.value
returns ''
in this case parseInt(e.target.value)
returns NaN
, because parseInt('')
returns NaN
., you need check it and set current
as empty string
handleChange(e) {
let val = parseInt(e.target.value);
if (isNaN(val)) {
this.setState({ current: '' });
} else {
if (val < 1) {
val = 1;
}
if (val) {
this.set(val);
}
}
}
Example
Remove value={this.state.current}
from the input
element