Updating the text box value via an OnChange event

  Kiến thức lập trình

I’m displaying and populating (from a data source) a set of records. But I am not able to change the values in the fields. Is the OnChange event set incorrectly? This is before any form submission – I just need to be able to change the display content of the text box via the UI. I’m wondering if it also needs the ID of the record being updated.

{cookies.map(cookie =>
   <form key={cookie.id}>
     <input type="text" onChange={handleInput}  value={cookie.id}></input>
     <input type="text" onChange={handleInput}  value={cookie.name}></input>
     <input type="text" onChange={handleInput}  value={cookie.desc}></input>
     <input type="text" onChange={handleInput}  value={cookie.price}></input>
     <input type="submit"></input>
  </form>
 )}

const [postdata, setPostdata] = useState({})

const handleInput = (event) => {
 setPostdata({ ...postdata, [event.target.name]: event.target.value })
}

For reference, here is the C# class…

public class Cookie
{
 public int Id { get; set; }

 public string? name { get; set; }

 public string? desc { get; set; }

 public double Price { get; set; }
}

2

In order to use event.target.name, the elements defined in html / jsx need to have the name attribute defined. For example, for the id input, if postData expects an id attributed, you would need

<input type="text" onChange={handleInput} name="id" value={cookie.id}></input>

rather than

<input type="text" onChange={handleInput} value={cookie.id}></input>

because without that, there’s actually no way for the form to know where to look for the data.

LEAVE A COMMENT