Allow users to type dynamic option (autotag) in jQuery Select2 DropDownList in ASP.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

Hello, 

I'm using a textbox that accepts multiple values with search functionality. Now, the problem is that it's not allowing me to enter values which are not already in the dropdownlist.

I tried jquery plugin but it's not working currently. below is my code:

References:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $(".js-example-placeholder-single").select2({
            placeholder: "select technologies that you've experience in",
            allowClear: true
        });
        $('[id*=ddl1]').on('change', function () {
            $('[id*=hfCourses]').val($(this).val());
            //hfCourses
        });
        $('[id*=ddl1]').keydown(function (e) {
            if (e.keyCode == 13 || e.keyCode == 32) {
                //alert('You Press enter');
                var getValue = $(this).val();
                $('[id*=ddl1]').append('<span class="email-ids">' + getValue + ' <span class="cancel-email">x</span></span>');
                $(this).val('');
            }
        });
    });
</script>

ASPX Markup:

<div class="col-md-6">
    <div class="form-group">
        <label>Technologies</label>
        <asp:DropDownList ID="ddl1" runat="server" multiple="multiple" 
            CssClass="form-control js-example-placeholder-single form-control ddl1"
            ToolTip="Select ">
            <asp:ListItem>C/CPP</asp:ListItem>
            <asp:ListItem>JAVA</asp:ListItem>
            <asp:ListItem>C#</asp:ListItem>
            <asp:ListItem>PYTHON</asp:ListItem>
            <asp:ListItem>PHP</asp:ListItem>
            <asp:ListItem>ANGULAR</asp:ListItem>
            <asp:ListItem>Android</asp:ListItem>
            <asp:ListItem>IOS</asp:ListItem>
            <asp:ListItem>XML</asp:ListItem>
            <asp:ListItem>WCF</asp:ListItem>
        </asp:DropDownList>
    </div>
</div>

 

Posted 2 months ago

Hi jmprateek,

Set the tags attribute true to allow you adding new tag taht are not in the list.

$(".js-example-placeholder-single").select2({
    placeholder: "select technologies that you've experience in",
    allowClear: true,
    tags: true
});