Neville Lobotom
Neville Lobotom

Reputation: 127

Open Select2 dropdown with JS click()

I've tried simulating click with .click() function on every element within the container including the container itself. The dropdown won't open. Clicking with mouse works as it should.

<div class="select2-container select2-allowclear editor s-LookupEditor valid" id="s2id_AbCd_Q_CustomerEditDialog22_CstId">
<a href="javascript:void(0)" class="select2-choice" tabindex="-1">   
    <span class="select2-chosen" id="select2-chosen-2">Peter Smith</span>
    <abbr class="select2-search-choice-close"></abbr>   
    <span class="select2-arrow" role="presentation">
        <b role="presentation"></b>
    </span>
</a>
<label for="s2id_autogen2" class="select2-offscreen">Customer</label>
<input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-2" id="s2id_autogen2">

Upvotes: 2

Views: 1675

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

To open a Select2 instance programmatically, invoke the open method on it:

$('select').select2(); // initialise

$('select').select2('open'); //open
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select>
  <option>Please select</option>
  <option>Foo</option>
  <option>Bar</option>
</select>

Upvotes: 2

Related Questions