英文:
How to get values using select2 in JQuery
问题
我有多个选择框,其中包含语言选项,我想获取所选的值。
我尝试从id中检索值,但控制台中没有显示任何内容。
$('#language').select2();
<select id="language" class="form-control" multiple="multiple" data-toggle="select2">
<option value="1">FR</option>
<option value="1">Eng</option>
<option value="1">Es</option>
</select>
var selectedValues = $('#language').val();
console.log(selectedValues);
英文:
I have multiple select that contains options of languages and I want to get the values selected.
I tried that using by retrieve the value from the id but nothing shown in the console.
$('#language').select2();
<select id="language" class="form-control" multiple="multiple" data-toggle="select2">
<option value="1">FR</option>
<option value="1">Eng</option>
<option value="1">Es</option>
</select>
var selectedValues = $('#language').val();
console.log(selectedValues);
答案1
得分: 0
你可以尝试这样做:
var selectedValues = $('#language').find(':selected').val();
console.log(selectedValues);
英文:
You can try this..
var selectedValues = $('#language').find(':selected').val();
console.log(selectedValues);
答案2
得分: 0
selectedValues = $('#language').val(); 将为您提供所选选项的值数组。
以下是一个演示:
$('#language').select2().on('change', function(e) {
var selectedValues = $('#language').val();
console.log(selectedValues);
});
您可以在此示例中看到如何使用 Select2 插件来获取所选选项的值。
英文:
selectedValues = $('#language').val();
will give you the array of values of selected options.
Here is a demo:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('#language').select2().on('change', function(e) {
var selectedValues = $('#language').val();
console.log(selectedValues);
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="language" class="form-control" multiple="multiple" data-toggle="select2">
<option value="1">FR</option>
<option value="2">Eng</option>
<option value="3">Es</option>
</select>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论