i have a array called students, it stores name, age and phone number, i already have the functionality of the add fuction:
const [students, setStudents] = useState([]);
const [name, setName] = useState("");
const [age, setAge] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
And i have already have the update functionality"
const [updatedName, setupdatedName] = useState("");
const [updatedAge, setupdatedAge] = useState("");
const [updatedPhoneNumber, setupdatedPhoneNumber] = useState("");
const updateStudent = () => {
if (updatedName.trim() === "" || updatedAge.trim() === "") {
showAlert("Name and Age are required fields.");
return;
}
if (!/^[a-zA-Z\s]+$/.test(updatedName.trim())) {
showAlert("Name must contain only letters and spaces.");
return;
}
const ageValue = parseInt(updatedAge);
if (isNaN(ageValue) || ageValue < 1 || ageValue > 100) {
showAlert("Age must be a number between 1 and 100.");
return;
}
const updatedStudents = [...students];
updatedStudents[selectedItemIndex] = {
name: updatedName,
age: parseInt(updatedAge),
phoneNumber:
updatedPhoneNumber.trim() === "" ? "N/A" : updatedPhoneNumber,
};
setStudents(updatedStudents);
setupdatedName("");
setupdatedAge("");
setupdatedPhoneNumber("");
handleClose2();
setAlert(null);
};
i have a modal that opens when the user clicks on the update button: and it has the form inside it:
<form>
<div className="m-3">
<label htmlFor="exampleInputEmail1" className="form-label">
Name:
</label>
<input
type="text"
value={updatedName}
onChange={(e) => {setupdatedName(e.target.value);}}
className="form-control"
/>
</div>
...
there is similar inputs for age and phone number
how can i place the old value of the name, so that i can edit or leave the value same as it and edit other values like age and phone number.
also along with this: there is another use case i want to do: so when the user puts a phone number it should be either 10 digits(i need to alrert if its not 10 digits) or it should be null
Via Active questions tagged javascript - Stack Overflow https://ift.tt/zN8KLeJ
Comments
Post a Comment