Bootstrap select - 获取选定的值

时间:2016-08-25 14:26:18

标签: jquery bootstrap-select

参考:https://silviomoreto.github.io/bootstrap-select/options/

我在我的页面上使用上面的内容允许我的用户选择多个值。 但是我想简单地显示所选值的文本,但它要么不可能,要么我做错了? 我得到所有的值,并希望“选定”的值 因为我想稍后向用户显示结果......

<div class="form-group"><label class="col-lg-2 control-label">Service(s):</label>
    <div class="col-lg-9">
    <select class="selectpicker" multiple title="Select from the following..." data-width="100%" id="serviceList">
    </select></div></div>

    <script>
    var services = [{"value":"3e197221-e48b-44b8-a2aa-2054638f3bbc","label":"Service1","price":30.000000},{"value":"cd909812-ff6e-484b-96e3-c344ba20e140","label":"Service2","price":10.000000}];
    $('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
            var v = $(".selectpicker option:selected").val();
            var result =[];
            for (var i = 0; i < services.length; i++){
                // look for the entry with a matching value
                if (services[i].value === v) {
                    result.push(services[i].label);
                    console.log(services[i].label);
                }
            }
            for (i = 0; i < result; i++) {
                console.log(result[i]);
            }

        });
    </script>

2 个答案:

答案 0 :(得分:2)

您想要“摘取”所选选项数组中的所有标签。

$('.selectpicker').on('changed.bs.select', function () {

    selectedServices = $.map($(this).find("option:selected"), function(o) { return o["label"]; });

}

答案 1 :(得分:0)

这很有效,看起来很长。

var selectedServices =[];
$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {



        for (var key in services) {
            if (key == clickedIndex) {
                console.log(key + ' is ' + services[key]);
                selectedServices.push(services[key].label);
                console.log(services[key].label);
            }

        }