2

I have a simple SELECT2 setup like this:

<select name="cat" id="cat" class="js-example-basic-single">
    <option value="URL.com">Option 1</option>
    <option value="URL2.com">Option 2</option>
</select>

I'm curious how I can make these options clickable so that once clicked or found during a search, they instantly go to the URL in value="".

My header contains:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
        $(".js-example-basic-single").select2();
        });
    </script>

I'm aware there is documentation online, but it doesn't cover my specific request.

stylusss
  • 79
  • 2
  • 10
  • Can you elaborate on specifically what you mean by "found during a search"? As far as clicking goes, there is the `select2:select` event that is emitted when an option is clicked (Ref. https://select2.org/programmatic-control/events), but I'm not 100% clear on what the first part entails. – Taplar Feb 21 '18 at 20:50
  • as in, when you type in the category to search through the options. Can you show me an example, I'm JavaScript illiterate. – stylusss Feb 21 '18 at 20:54
  • So you mean when the search results returns just a single result? – Taplar Feb 21 '18 at 20:57
  • You need write on change function, when selection is changed, catch seleced data and redirect to url – Zeljka Feb 21 '18 at 21:03
  • Taplar: Remember you can click the select and search, that's what I mean. After the option is found, you click enter and it goes to its respective URL. I need to see a working code. – stylusss Feb 21 '18 at 23:41

3 Answers3

5

As Taplar told you the documentation cover your request, you just need to manage the select2:select event and use it to open the url:

$("#cat").on("select2:select", function (e) {
    window.open(e.params.data.id);
});

If you want to open the url when searching and clicking enter it will be enough with the code above.

If you want to perform the same automatically when the search returns a single value use this code changing the operations to do when it matches just one result.

Hope this helps.

0

Here's what I did:

<script type="text/javascript">
        $(document).ready(function() {
        $(".js-example-basic-single").select2();

        $("#cat").on("select2:select", function (e) {
window.open(e.params.data.id);
});

        });
    </script>
stylusss
  • 79
  • 2
  • 10
0

If you are working with previous versions of select2 and above solutions doesn't work try this one:

    $("#cat").on("select2-selecting", function (e) {
    window.open(e.object.id);
});

It's hard to find older documentation for select2 so it might be useful for someone working on legacy code. Above code does not work with version 4.x of select2