przbadu przbadu - 2 years ago 201
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>

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:

// => []


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


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 Source

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'); 




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download