![](/img/trans.png)
[英]javaScript multiply two numbers and show the result into third html input
[英]Multiply values from two different input and show in the third input
我有一個表單,我正在使用 Formik 驗證表單,我想在有輸入時將數量輸入和單位成本輸入的值相乘,然后在總輸入中自動顯示它。 我正在使用 Formik + Chakra_UI。
<Formik
initialValues={{
productName: "",
productNumber: "",
unitCost: 0,
totalCost: 0,
quantity: 0,
}}
>
{({ values }) => (
<Form>
<Field name="productName">
{() => (
<Grid templateColumns="repeat(2, 1fr)" gap={5}>
<Box>
<FormControl>
<FormLabel htmlFor="productName">Product Name:</FormLabel>
<Input id="productName" placeholder="Product Name" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="productNumber">
Product Number:
</FormLabel>
<Input id="productNumber" placeholder="Product Number" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="quantity">Quantity:</FormLabel>
<Input id="quantity" placeholder="Quanity" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="unitCost">Unit Cost:</FormLabel>
<Input id="unitCost" placeholder="Unit Cost" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="totalCost">Total Cost:</FormLabel>
<Input id="totalCost" placeholder="Total Cost" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
</Grid>
)}
</Field>
<Button isFullWidth mt={6} colorScheme="green" type="submit">
Submit
</Button>
</Form>
)}
</Formik>
為了使狀態管理的代碼更短,您可以從values
刪除totalCost
並在使用時計算它。
更新后的代碼如下所示:
<Formik
initialValues={{
productName: "",
productNumber: "",
unitCost: 0,
quantity: 0,
}}
onSubmit={...}
>
{({ values }) => (
<Form>
<Grid templateColumns="repeat(2, 1fr)" gap={5}>
// ... other boxes stay same as before
<Box>
<FormControl>
<FormLabel htmlFor="totalCost">Total Cost:</FormLabel>
<Input id="totalCost" placeholder="Total Cost" value={values.quantity * values.unitCost} />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
</Grid>
<Button isFullWidth mt={6} colorScheme="green" type="submit">
Submit
</Button>
</Form>)}
</Formik>
然后您將對onSubmit
重復相同的計算。 應用一些四舍五入也是個好主意,因為我假設您將它用於貨幣value={values.quantity * values.unitCost}
也許你可以把它簡化為
<FormControl>
<FormLabel htmlFor="totalCost">Total Cost:</FormLabel>
<Box id="totalCost">{Math.round((values.quantity * values.unitCos + Number.EPSILON) * 100) / 100}</Box>
</FormControl>
此處解釋四舍五入: 四舍五入至最多 2 個小數位(僅在必要時)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.