Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display select2 as plain input text

I'm using select2 plugin (latest version 4.0.2) for autocomplete in my probject. I found that select2 can be applied only to select control. The main problem is that text input placed as first option of this control (see img below).

Is there any way to have text input placed instead of select control (like typeahead plugin)?

Some of screenshots (actually you can try it here)

Collapsed (you can see here only standard select html control with selected option)

enter image description here

Expanded (text input place as the first option of select control, text input hidden if select collapsed)

enter image description here

Typeahead (applied to directly input text, type query text in the first row that always displayed on the page)

enter image description here

like image 849
Adel Nazirov Avatar asked Sep 05 '26 12:09

Adel Nazirov


2 Answers

Hope this is what you're trying to achieve.

$(document).ready(function() {
$('#myInputEle').select2({
    width: '100%',
    allowClear: true,
    multiple: true,
    maximumSelectionSize: 1,
    placeholder: "Start typing",
    data: [
            { id: 1, text: "Nikhilesh"},
            { id: 2, text: "Raju"    }
          ]    
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/select2/3.4.8/select2.css" />

<input type="text" id="myInputEle"/>
like image 130
Nikhilesh Shivarathri Avatar answered Sep 07 '26 07:09

Nikhilesh Shivarathri


Here is the solution -

STEP 1 select2 code

$('#input').select2();

STEP 2 Add this CSS end of the select2.css -

.select2-dropdown--below {
  top: -38px; }

Please note : 38px is your input field height. You need to adjust your input height.

STEP 3 If you need to prevent select2 from flipping the dropdown upward

Open

select2.js

Find

var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);

Replace with

 var enoughRoomBelow = true;
 var enoughRoomAbove = false;

Done !

DEMO

Check my customize version here https://codepen.io/gtanim/pen/pWEdQj

like image 23
MD JAHIRUL ISLAM Avatar answered Sep 07 '26 09:09

MD JAHIRUL ISLAM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!