我想檢查用戶輸入的總價和接收價,其中接收價不應超過總價。
比如說,在 html 檔案中,我確實有 3 個輸入框。盒子A取總價,盒子B取卡收款價值,盒子C取現金收款價值。框 B 框 C 不應大于框 A。我需要對其進行驗證并停止提交。
if A >= B C : 允許提交表單
如果 A < B C : 不允許提交表單,需要顯示錯誤訊息,如“接收價值大于總價值”
這可能很簡單,因為我是 JS 新手,所以我把它貼在這里。
uj5u.com熱心網友回復:
下面介紹的是實作預期目標的一種可能方式。
代碼片段
// access the button from the html
const btn = document.getElementById("btnSubmit");
// access input boxes A, B, C
const [boxA, boxB, boxC] = [
document.getElementById("boxA"),
document.getElementById("boxB"),
document.getElementById("boxC"),
];
// a generic method to validate if prices indicate
// that 'submit' button should be disabled
// as well as render an error notification
const validatePrices = () => {
btn.disabled = (
boxA.value < boxB.value boxC.value
);
document.getElementById("error").innerText = (
boxA.value < boxB.value boxC.value
? 'Sum of Card Payment and Cash Payment exceeds Total Cost'
: ''
);
};
// add event-listener to each input to invoke the validate method
[boxA, boxB, boxC].forEach(
box => box.addEventListener('keyup', validatePrices)
);
// a placeholder 'click' action handler for the 'submit' button
btn.addEventListener(
'click', () => alert(
`
Valid prices received !
Cost: ${boxA.value}
Card payment: ${boxB.value}
Cash payment: ${boxC.value}
`
)
);
.error-text {
font-size: 14px;
color: red;
margin-top: 15px;
}
<label for="boxA">Total Cost: </label><input id="boxA" type="number"/><br/>
<label for="boxB">Card Payment: </label><input id="boxB" type="number"/><br/>
<label for="boxC">Cash Payment: </label><input id="boxC" type="number"/><br/>
<div id="error" class='error-text'></div><br/><br/>
<button id="btnSubmit">Submit</button>
解釋
添加到上述代碼段的行內注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493861.html
標籤:javascript 阿贾克斯
