Search field inside select box how to do?

3

I would like to know if there is any way to put a search field inside a select box, for example ... I have a selectbox with +3000 thousand items registered, there arises my need to have a search field to streamline the user side.

In the photo above is my normal select box with all items ...

Has anyone ever had this need? is it possible to do this with HTML and PHP?

    
asked by anonymous 16.09.2015 / 06:35

2 answers

1

You can use select2.js, it is a search component just like the select you are using, but it makes calls to the server with ajax by filtering by the value typed in it. I think that's what you need.

To use it is very easy Add these 2 files to the head of your site

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>

and to use it simply do the following:

Mount the html:

    <select class="js-data-example-ajax">
      <option value="3620194" selected="selected">select2/select2</option>
    </select>

and create the javascript responsible for configuring the component:

$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, page) {
      // parse the results into the format expected by Select2.
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data
      return {
        results: data.items
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatRepo, // omitted for brevity, see the source of this page
  templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

If you need more information just go to the official website: link

    
16.09.2015 / 14:59
0

You have a js plugin that calls Select2 . Take a look at the documentation for it.

Only import the face library:

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>

Then just do this:

$(document).ready(function() {
   $(".meuselect").select2();
});

<select class="meuselect">
  <option value="1">Opcao 99</option>
  ...
  <option value="99">Opcao 99</option>
</select>

Anything you need, you can call:)

    
16.09.2015 / 12:12