HTML双输入框联动开发需求:根据余额输入值自动设置状态输入框内容
Solution for Auto-Filling Status Based on Balance Amount Input
Got it, here's a straightforward implementation that does exactly what you need—linking the balance amount input to auto-update the status field. Below is the complete, runnable code:
<label>Balance Amount</label> <input type="text" name="balance_amount" id="balanceAmount"><br><br> <label>Amount Status</label> <input type="text" name="status" id="statusField" readonly><br><br> <script> // Grab references to both input elements const balanceInput = document.getElementById('balanceAmount'); const statusInput = document.getElementById('statusField'); // Function to update the status based on balance value function updatePaymentStatus() { // Convert input value to a number, handle empty/non-numeric inputs const balance = parseFloat(balanceInput.value); // Core logic: check if balance is a valid number and match conditions if (!isNaN(balance) && balance === 0) { statusInput.value = 'PAID'; } else if (!isNaN(balance) && balance !== 0) { statusInput.value = 'NOT PAID'; } else { // Clear status if input isn't a valid number (adjust this if needed) statusInput.value = ''; } } // Listen for any input changes to update status in real-time balanceInput.addEventListener('input', updatePaymentStatus); // Initialize status on page load in case there's a default value updatePaymentStatus(); </script>
Key Notes:
- Added
idattributes to the inputs for easier DOM targeting (you could also usedocument.querySelector('[name="balance_amount"]')if you prefer sticking with names) - Marked the status input as
readonlyso users can't manually edit it—keeps the status tied strictly to the balance amount - Included
isNaNchecks to handle cases where users enter non-numeric values (like letters or symbols) without breaking the logic - Used the
inputevent instead ofchangeso the status updates immediately as the user types, not just when they click away
Test it out: type 0 in the balance field, and the status will jump to "PAID"; type any other valid number (1, 100, 50.50, etc.) and it'll show "NOT PAID". If you enter something non-numeric, the status field clears out (feel free to tweak that else block if you want a different behavior here).
内容的提问来源于stack exchange,提问作者user12380208
相关产品推荐
相关产品推荐

