Rafael
Rafael

Reputation: 2188

Jquery Select 2 not showing selected value

Select2 plugin is not showing selected option with templateFormat option Anyone knows how fix it ?

markup:

<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
}

here is a fiddle of the above code

Thank you

Upvotes: 3

Views: 6491

Answers (2)

Raj Soni
Raj Soni

Reputation: 89

A very simple way to tackle this problem is :

// 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();

Upvotes: 0

Bindrid
Bindrid

Reputation: 3735

I figured it out. Made the following change and it started working. I added templateSelection.

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

Upvotes: 2

Related Questions