如何使用 select2 从 html 中接收 JS 选择
How to receive in JS selections from html using select2
我想在 JS 中接收来自 html 的 selected 值。在 html 中,我将 multi-select 框与 selected2 库一起使用。我能够为 <select class="form-control" id="companies" >
这样的普通单一选择做到这一点。
谁能告诉我如何用 select2 为多个 select 做这件事?
html
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<form>
<div class="form-group">
<label>Airline companies</label>
<p>
<select class="js-example-basic-multiple" id="companies" name="states[]" multiple="multiple" style="width: 120%">
<!-- select class="form-control" id="companies" --> // if I don't use multiple select with select2, it worked
<option selected>Select companies</option>
<option value="one">First</option>
<option value="two">Second</option>
...
</select>
</p>
</div>
<button class="btn btn-primary" type='button' id="button">Refresh</button>
</form>
JS
company = getSelectedOption('companies')
function getSelectedOption(id){
/* function to get the selected value from the dropdowns */
let select = document.getElementById(id);
let value = select.options[select.selectedIndex].value;
return value
}
您可以使用 jQuery 方法获取选定的值 .val()
:
var company = getSelectedOption('companies');
function getSelectedOption(id){
return $('#' + id).val();
}
我想在 JS 中接收来自 html 的 selected 值。在 html 中,我将 multi-select 框与 selected2 库一起使用。我能够为 <select class="form-control" id="companies" >
这样的普通单一选择做到这一点。
谁能告诉我如何用 select2 为多个 select 做这件事?
html
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<form>
<div class="form-group">
<label>Airline companies</label>
<p>
<select class="js-example-basic-multiple" id="companies" name="states[]" multiple="multiple" style="width: 120%">
<!-- select class="form-control" id="companies" --> // if I don't use multiple select with select2, it worked
<option selected>Select companies</option>
<option value="one">First</option>
<option value="two">Second</option>
...
</select>
</p>
</div>
<button class="btn btn-primary" type='button' id="button">Refresh</button>
</form>
JS
company = getSelectedOption('companies')
function getSelectedOption(id){
/* function to get the selected value from the dropdowns */
let select = document.getElementById(id);
let value = select.options[select.selectedIndex].value;
return value
}
您可以使用 jQuery 方法获取选定的值 .val()
:
var company = getSelectedOption('companies');
function getSelectedOption(id){
return $('#' + id).val();
}