In this code example I would like to try to do easy math (ket=name names). The sum should be a number and displayed as “ket”. But when I type in 3 and 6 in my input fields, “ket” shows up to be 36 (and not 9).
export default function Kettenl() {
const submitContact = async (event) => {
event.preventDefault();
const names = event.target.names.value;
const name = event.target.name.value;
let ket = name names;
alert(`So your name is ${ket}?`);
};
return (
<div className="max-w-xs my-2 overflow-hidden rounded shadow-lg">
<div className="px-6 py-4">
<div className="mb-2 text-xl font-bold">Contact us</div>
<form className="flex flex-col" onSubmit={submitContact}>
<label htmlFor="name" className="mb-2 italic">
Name
</label>
<input
className="mb-4 border-b-2"
id="name"
name="name"
type="number"
required
/>
<label htmlFor="name" className="mb-2 italic">
Names
</label>
<input
className="mb-4 border-b-2"
id="names"
name="names"
type="number"
required
/>
<button
type="submit"
className="px-4 py-2 font-bold text-white bg-blue-500 rounded-full hover:bg-blue-700"
>
Submit
</button>
</form>
</div>
</div>
);
}
CodePudding user response:
That is because the values are being read as strings '3' '6'='36' you should change it to this
const names = parseInt(event.target.names.value);
const name = parseInt(event.target.name.value);
Also, you are storing and accessing the values incorrectly. You should learn the basics of react before moving on to next.js. https://reactjs.org/docs/forms.html Read about controlled and uncontrolled inputs from the docs So even if your app works with the aforementioned change, you shouldn't be doing it like this.
CodePudding user response:
Thats because values are returned as a string by default from your target element. For inputs with type="number"
you can just use the input value with e.target.names.valueAsNumber
.
const submitContact = async (event) => {
event.preventDefault();
const names = event.target.names.valueAsNumber;
const name = event.target.name.valueAsNumber;
let ket = name names;
alert(`So your name is ${ket}?`);
};