【问题标题】:How to receive in JS selections from html using select2如何使用select2从html接收JS选择
【发布时间】:2020-05-01 20:19:06
【问题描述】:

我想在 JS 中接收来自 html 的选定值。在 html 中,我使用带有 selected2 库的多选框。我可以通过普通的单一选择来做到这一点,例如<select class="form-control" id="companies" >

谁能告诉我如何使用 select2 进行多项选择?

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
}

【问题讨论】:

    标签: javascript html jquery-select2 multiple-select


    【解决方案1】:

    您可以使用jQuery方法.val()获取选择值:

    
    var company = getSelectedOption('companies');
    
    function getSelectedOption(id){
        return $('#' + id).val();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 2013-01-11
      • 2023-03-10
      • 2023-03-28
      • 2020-05-29
      • 1970-01-01
      相关资源
      最近更新 更多