如何在Bootstrap表单中根据下拉选择切换输入框符号显示
实现Bootstrap表单金额/百分比输入框动态切换
直接复制下面的完整代码就能实现你要的功能,我会把关键部分拆解开讲明白:
<!DOCTYPE html> <html lang="zh-CN"> <head> <!-- 引入Bootstrap样式,也可以替换成你本地的Bootstrap CSS文件 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <div class="mb-3"> <label for="quoteType" class="form-label">报价模式/类型</label> <select class="form-select" id="quoteType" onchange="togglePriceInput()"> <option value="fixed">固定费率</option> <option value="percentage">百分比</option> </select> </div> <div class="mb-3"> <label for="price" class="form-label">价格/比例</label> <div class="input-group"> <!-- 美元前缀,默认显示 --> <span class="input-group-text" id="dollarPrefix">$</span> <input type="number" class="form-control" id="price" placeholder="请输入金额"> <!-- 百分比后缀,默认隐藏 --> <span class="input-group-text d-none" id="percentSuffix">%</span> </div> </div> </div> <!-- 引入Bootstrap的JS(可选,保证组件样式正常),也可以用本地文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> // 核心切换逻辑函数 function togglePriceInput() { // 获取下拉框选中的模式 const selectedType = document.getElementById('quoteType').value; // 获取前缀、后缀和输入框元素 const dollarPrefix = document.getElementById('dollarPrefix'); const percentSuffix = document.getElementById('percentSuffix'); const priceInput = document.getElementById('price'); if (selectedType === 'percentage') { // 切换到百分比模式:隐藏美元前缀,显示百分比后缀,更新输入提示 dollarPrefix.classList.add('d-none'); percentSuffix.classList.remove('d-none'); priceInput.placeholder = "请输入百分比"; } else { // 切换回固定费率模式:恢复美元前缀,隐藏百分比后缀,改回金额提示 dollarPrefix.classList.remove('d-none'); percentSuffix.classList.add('d-none'); priceInput.placeholder = "请输入金额"; } } </script> </body> </html>
关键部分说明
- HTML结构:
- 下拉框绑定了
onchange="togglePriceInput()",意思是每次切换选项时自动触发切换函数。 d-none是Bootstrap自带的隐藏类,加这个类元素就会隐藏,移除就会显示,不用自己写复杂样式。
- 下拉框绑定了
- JS函数:
- 先拿到下拉框的选中值,再判断当前是哪种模式。
- 用
classList.add和classList.remove控制前缀后缀的显示状态,逻辑简单直观。 - 顺便修改输入框的占位提示,让用户清楚该输入什么类型的内容。
注意事项
- 确保你已经引入了Bootstrap的CSS(代码里的CDN链接可以直接用,也可以换成你本地的Bootstrap文件)。
- 输入框用了
type="number",限制用户只能输入数字,避免无效内容。 - 如果你的表单已有其他结构,直接把对应的下拉框和输入组部分替换过去,函数粘到页面的
<script>标签里就行。
内容的提问来源于stack exchange,提问作者Jarrod Estepp
相关产品推荐
相关产品推荐

