我试图使用选择器的选定选项的值进行DOM操作。我想要的是获取选择器的值id="service_provider_select"
首先打印。我使用选择器更改选项,当我运行console.log(input)
时,每次我都将Dialog
作为控制台中的打印值。
如何获取最近选择的值?
.HTML
<select class="selectpicker form-control item_select" id="service_provider_select" name="service_provider_select" data-size="5" data-live-search="true">
<option value="">Select Sevice Provider</option>
<option value="Dialog"> Dialog </option>
<option value="Mobitel"> Mobitel </option>
<option value="Airtel"> Airtel </option>
<option value="Hutch"> Hutch </option>
</select>
JAVASCRIPT
<script>
$(document).ready(function()
{
$(".selectpicker").selectpicker();
$('#service_provider_select').on("click", function()
{
input = $('#service_provider_select').val();
console.log(input);
});
});
var input = "Dialog";
</script>
我为您的问题创建了一个似乎对我有用的工作片段,看看它是否也适合您。
$(document).ready(function() {
$(".selectpicker").selectpicker();
// Fire event on change instead of on click
$('#service_provider_select').on("change", function() {
input = $('#service_provider_select').val();
console.clear();
console.log(input);
});
});
var input = "Dialog";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
<select class="selectpicker form-control item_select" id="service_provider_select" name="service_provider_select" data-size="5" data-live-search="true">
<option value="">Select Sevice Provider</option>
<option value="Dialog"> Dialog </option>
<option value="Mobitel"> Mobitel </option>
<option value="Airtel"> Airtel </option>
<option value="Hutch"> Hutch </option>
</select>