przbadu przbadu - 6 months ago 43
Javascript Question

programmatically select select2 options using jquery

I tried below solutions to select one of the listed options

<select data-placeholder="Company Name" class="select required form-control select2-hidden-accessible" name="company[company_name]" id="company_company_name" tabindex="-1" aria-hidden="true">
<option value=""></option>
<option value="ABC">ABC</option>
<option value="XYZ Company">XYZ Company</option>
<option value="PQR Company">PQR Company</option>
</select>


I have tried:

// Not working
$('#company_company_name').select2('val', 'XYZ Company');
// => undefined

// Not Working
$('#company_company_name').select2('val', 'XYZ Company', true);
// => undefined

// Not Working
$('#company_company_name').select2('data', {id: 'XYZ Company');
// => undefined

// Not working
$('#company_company_name').select2('data', {id: 'XYZ Company', a_key: 'XYZ Company');
// => undefined


ALSO NOTE below code is returning empty array:

$('#company_company_name').select2('data')
// => []


QUESTION

How can I select select2 options that already exists using jquery?

UPDATE

I also tried to select value and trigger the change, but then, select2 is broken and I can see simple select field

$('#company_company_name').val('XYZ Company').trigger('change');

Answer

What events does Select2 listen for?

Select2 will listen for the change event on the that it is attached to. If you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.

$('#company_company_name').val('XYZ Company'); 

Then

$('#company_company_name').trigger('change'); 

Or

$('#company_company_name').trigger('change.select2');
Comments