javascript - 如何使用 vanilla JavaScript 选择下拉选项?
问题描述
我正在尝试使用 JavaScript 在下拉菜单中选择一个选项,但我似乎找不到任何方法来做到这一点。目标是在选择特定选项时显示特定输入字段。相反,如果未选择任何内容,则隐藏输入字段。
目前,当您选择一个选项时,没有任何反应。我为此使用香草 JavaScript,没有 jQuery。
const variableFee = document.getElementById('variableFee').value = "Variable";
const fixedFee = document.getElementById('fixedFee').value = "Fixed";
const feeChoice = document.getElementById('feeChoice');
// ---------------- Fixed VS Variable Fee Calculation ---------------- //
// ------------------------------------------------------------------- //
function transactionFeeInput() {
if (feeChoice == variableFee) {
variableFee.style.display = "block";
}
}
#variableFeeInput, #fixedFeeInput {
display: none;
}
<div id="transactionFeeSection">
<h3>What is the transaction fee?</h3>
<label for="feeChoice"></label>
<select name="feeChoice" id="feeChoice">
<option id="blankOption" selected="true" disabled="disabled">-- Select an Option --</option>
<option id="variableFee" value="variable">Variable</option>
<option id="fixedFee" value="fixed">Fixed</option>
</select>
<input id="variableFeeInput" type="number" placeholder="Enter Percentage - 0%">
<input id="fixedFeeInput" type="number" placeholder="Enter Amount - $0.00">
</div>
我没有看到任何控制台错误,所以我不确定要修复什么?
解决方案
const variableFee = document.getElementById('variableFeeInput');
const fixedFee = document.getElementById('fixedFeeInput');
const feeChoice = document.getElementById('feeChoice');
// ---------------- Fixed VS Variable Fee Calculation ---------------- //
// ------------------------------------------------------------------- //
function transactionFeeInput() {
if (feeChoice.value == 'variable') {
variableFee.style.display = "inline-block";
fixedFee.style.display = "none";
}else{
fixedFee.style.display = "inline-block";
variableFee.style.display = "none";
}}
#variableFeeInput, #fixedFeeInput {
display: none;
}
<div id="transactionFeeSection">
<h3>What is the transaction fee?</h3>
<label for="feeChoice"></label>
<select name="feeChoice" id="feeChoice" onchange="transactionFeeInput()">
<option id="blankOption" selected="true" disabled="disabled">-- Select an Option --</option>
<option id="variableFee" value="variable">Variable</option>
<option id="fixedFee" value="fixed">Fixed</option>
</select>
<input id="variableFeeInput" type="number" placeholder="Enter Percentage - 0%">
<input id="fixedFeeInput" type="number" placeholder="Enter Amount - $0.00">
</div>
推荐阅读
- swift - 滚动视图中的 SwiftUI HStack 未正确显示图像
- javascript - Apple 的 Safari 浏览器使用什么 JavaScript 引擎?
- ios - 如何通过快速点击按钮来增加标签的数量?
- tensorflow - 如何获取车牌上每个符号的边界框
- python - Matplotlib 直方图移动 xticks
- amazon-web-services - 获取 SageMaker 中每个数据点的异常分数?
- php - 如何在 Laravel 日志中向 Google Stackdriver 注入自定义信息
- discord - discord.py 机器人重复消息
- java - 如何修复声纳“确保散列数据在这里是安全的”安全问题
- reactjs - 反应钩子:在渲染方法中使用(错误:无效的钩子调用)