Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use select2.js

I want to add a form field which can auto fill text & can take multiple tabs(similar to fb). I found select2.js helps me do it, But i am having problems in using it when i set multiple attribute to true. if i add multiple: true, the page dispalys it as a normal select.

I find documentation on select2 page confusing.

I am a new to all of them, Please help me out.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript" src="select2.js"></script>          

 <link href="select2.css" rel="stylesheet"/>
    <script src="select2.js"></script>
    <script>
        $(document).ready(function() { 
        $("#e1").select2([multiple: true]);
        });
    </script>

</head>
<body>
<input type="button" id="123">click
</br>
<input type="hidden" id="1234">
<select id="e1">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>

        <option value="WY">Wyoming</option>
    </select>

</body>
</html>
like image 637
petarap Avatar asked Jan 28 '13 09:01

petarap


People also ask

What is Select2 in Javascript?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

Do I need jQuery for Select2?

Select2 will register itself as a jQuery function if you use any of the distribution builds, so you can call . select2() on any jQuery selector where you would like to initialize Select2.

What Select2 dropdown?

By default, Select2 will attach the dropdown to the end of the body and will absolutely position it to appear above or below the selection container. Select2 will display the dropdown above the container if there is not enough space below the container, but there is enough space above it.


2 Answers

Add the attribute "multiple", and a width as well, only in the markup.

<select multiple id="e1" style="width:300px">

and js as this:

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

See fiddle here: http://jsfiddle.net/marcusasplund/jEADR/2/

A side note; you are loading select2.js 2 times in the code posted in your question.

like image 197
MarcusAsplund Avatar answered Nov 24 '22 14:11

MarcusAsplund


You can override the class specific for select2.js:

.select2-container-multi .select2-choices {
    width: 150px;
}

It should work.

like image 29
Kanan Farzali Avatar answered Nov 24 '22 14:11

Kanan Farzali