2016-11-02 77 views
1

我使用選擇二如下:如何在Select2中從數據源設置數據*?

$('select#fields').select2({ 
    placeholder: 'Select a field', 
    data: data.fields 
}); 

data.fields是這樣一個JSON:

"fields": [ 
    { 
    "id": "companies_id", 
    "text": "companies_id", 
    "data-type": "int" 
    }, 
    { 
    "id": "parent_companies_id", 
    "text": "parent_companies_id", 
    "data-type": "int" 
    }, 
    { 
    "id": "client_of_companies_id", 
    "text": "client_of_companies_id", 
    "data-type": "int" 
    }, 
    { 
    "id": "asset_locations_id", 
    "text": "asset_locations_id", 
    "data-type": "int" 
    }, 
    { 
    "id": "companies_name", 
    "text": "companies_name", 
    "data-type": "varchar" 
    }, 
    { 
    "id": "companies_number", 
    "text": "companies_number", 
    "data-type": "varchar" 
    } 
] 

idtext用於填充選項值,我可以使用第三值data-type和將它設置爲<option>的屬性?如果是這樣如何?任何可以給我一個例子嗎?

+0

可能會嘗試與[模板]的東西(https://select2.github.io /examples.html#templating)。 –

+0

@lamelemon,實際上這裏不需要模板。你可以檢查我的答案:) – Dekel

回答

1

其實 - 選擇2默認保存所有在<option>元素的data('data')變量的屬性,它創造的,你可以隨時使用$(<option>).data('data')訪問這些值,但請記住,它不是一樣.data('type')data-type="value"。您需要使用屬性的完整名稱。

下面是如何獲得select事件的data-type價值的例子:

var $example = $("#s1").select2({ 
 
    data: [ 
 
     { 
 
      "id": "companies_id", 
 
      "text": "companies_id", 
 
      "data-type": "int", 
 
      "data-extra": '1' 
 
     }, 
 
     { 
 
      "id": "parent_companies_id", 
 
      "text": "parent_companies_id", 
 
      "data-type": "int", 
 
      "data-extra": '2' 
 
     }, 
 
     { 
 
      "id": "client_of_companies_id", 
 
      "text": "client_of_companies_id", 
 
      "data-type": "int", 
 
      "data-extra": '3' 
 
     }, 
 
     { 
 
      "id": "asset_locations_id", 
 
      "text": "asset_locations_id", 
 
      "data-type": "int", 
 
      "data-extra": '4' 
 
     }, 
 
     { 
 
      "id": "companies_name", 
 
      "text": "companies_name", 
 
      "data-type": "varchar", 
 
      "data-extra": '5' 
 
     }, 
 
     { 
 
      "id": "companies_number", 
 
      "text": "companies_number", 
 
      "data-type": "varchar", 
 
      "data-extra": '6' 
 
     } 
 
    ], 
 
}).on('select2:select', function(e) { 
 
    console.log(e.params.data['data-type'], e.params.data['data-extra']); 
 
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" /> 
 
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script> 
 
<select id="s1"> 
 
</select>

+0

@ReynierPM,謝謝你接受答案。投票也將不勝感激。 – Dekel

+0

我已經投票了;)雖然這比我更復雜,但我會開一個新的話題,希望你能幫助我以及 – ReynierPM

+0

發佈到新主題的鏈接 – Dekel