select 实现选中一个特定的选项后切换为输入模式
效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>input模拟select</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"></script>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.input_select {
position: relative;
}
.select_option {
position: absolute;
top: 32px;
z-index: 10;
display: none;
width: 100%;
margin: 0;
padding: 5px 0 5px 0;
list-style: none;
border: 1px solid #c4c4c4;
background-color: white;
}
.select_option li {
width: 100%;
padding-left: 10px;
line-height: 20px;
}
.select_option li:hover {
background-color: #0075ff;
color: white;
}
</style>
</head>
<body>
<div class="input-group" style="width: 250px;">
<span class="input-group-addon">货币</span>
<div class="input_select">
<input name="product_rate" class="form-control select" placeholder="请选择" type="text" />
<ul class="select_option">
<li>6</li>
<li>13</li>
<li>请输入其他税率(1-100)</li>
</ul>
</div>
</div>
<script>
$(() => {
$('.input_select .select').click(function () {
$(this).blur()
$(this).next().slideDown()
$(this).attr("placeholder", "请选择")
})
.keyup(function () {
this.value = this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''
})
.change(function () {
let val = $(this).val();
$(this).val(parseFloat(val))
})
$('.input_select .select_option li').click(function () {
let selectedVal = $(this).text();
if (selectedVal === "请输入其他税率(1-100)") {
$(this).parent().prev().val('');
$(this).parent().prev().focus();
$(this).parent().prev().attr("placeholder", "请输入其他税率(1-100)")
} else {
$(this).parent().prev().val(selectedVal);
}
$(this).parent().slideUp();
})
})
</script>
</body>
</html>
$(this).parent().slideUp();
})
})