2016-01-20 161 views
1

Select2插件未顯示帶有templateFormat選項的選定選項 任何人都知道如何修復它?Jquery選擇2未顯示選定值

標記:

<select id="plans" style="width: 75%"> 
<option value="1" name="text1" price="$1" saving="text" selected="selected"></option> 
<option value="2" name="text2" price="$2" saving="text" selected="selected"></option> 

JS:

$(document).ready(function() { 
$('select#plans').select2({ 
    minimumResultsForSearch: Infinity, 
    templateResult: formatState 
}); 
}); 
function formatState(state) { 
if (!state.id) return state.text; 
var html = '<span class="name">' + state.element.attributes.name.value + "</span>" 
html += '<span class="price">' + state.element.attributes.price.value + </span>" 
html += '<span class="saving">' + state.element.attributes.saving.value + "</span>" 
var $state = $(html); 
return $state 
} 

這裏是上面的代碼的fiddle

謝謝

回答

1

我figu衝出來。做了以下更改並開始工作。我添加了templateSelection。

$(document).ready(function(){ 
$('select#plans').select2(
     {minimumResultsForSearch: Infinity, 
      templateResult: formatState, 
     templateSelection:formatState 
    });  
    }); 
+0

是,它的工作......非常感謝你 – Rafael

0

一個非常簡單的方法來解決這個問題是:

// Step1: Here assuming id of your selectbox is my_id, so this will add selected attribute to 1st option 
$('#my_id option').eq(0).prop('selected',true); 


// Step2: Now reinitialize your select box 

// This will work, if you haven't initialized 
selectbox $('#my_id').select2(); 

or 

//This will work, if you have initialized selectbox earlier, so destroy it 
    first and initialise it 
$('#my_id').select2('destroy').select2();