I am trying to handle dynamic onchange name input within an array.I am calling a function for setting the total number of input.Based on the list size no of input boxes will be placed.
componentDidMount() {
this.handleLevelNum();
}
handleLevelNum() {
const levelNum = [];
var getValue = 2;
if(getValue > 0) {
var i;
for (i = 1; i <= getValue; i++) {
console.log(getValue)
levelNum.push({
'cogsId': i,
'riskFactor': ''
});
this.setState({
levelNum: levelNum,
});
}
console.log("print level number",levelNum)
}
else{
this.setState({
levelNum: [],
});
}
}
<Grid container spacing={24}>
{
this.state.levelNum.map((design, key) =>
<Grid item xs={12} >
<input style={{width:'100px'}}
type="text" onChange={this.handleCogsId(design.cogsId} placeholder=""/>
<input name="col2"
onChange={this.handleRiskFactor(design.cogsId)} value={this.state.riskFactor}
type="text" placeholder=""/>
<input name="col2"
onChange={this.handlePrice(key)} value={this.state.price}
type="text" placeholder=""/>
</Grid>
)}
<button type="button" onClick={this.saveProjectFileItem} >Submit</button>
These are the onchange function i wrote:
handleRiskFactor = key => evt => {
const newlevelNum = this.state.levelNum.map((design, sidx) => {
if (key !== sidx) return design;
return { ...design,cogsId:'', riskFactor: evt.target.value };
});
this.setState({ levelNum: newlevelNum });
};
handleCogsId = key => evt => {
const newlevelNum = this.state.levelNum.map((design, sidx) => {
if (key !== sidx) return design;
return { ...design,cogsId:key, riskFactor: ''};
});
this.setState({ levelNum: newlevelNum });
};
Now if the the index size is 2 no of input boxes will be placed accordingly.First input box will contain the value of the id from database and second input box will have an onchange event which value will be set with the first input id.I want to save the value like this in onchange event.The idea is to save an array like this based on onchange event of the input box:
{
"levelNum": [
{
"cogsId": "1",
"riskFactor": "critical"
},
{
"cogId": "2",
"riskFactor": "None"
}
]
}
Right now i am not being able to type anything in input box except the last one.But i am not being able to manipulate it dynamically.How can i manipulate it? any help regarding manipulating this dynamic input in onchange will be appreciated.