utkarsh2k2 utkarsh2k2 - 1 year ago 256
jQuery Question

Multiple select field (Jquery Select2 plugin)

I am using Jquery Select2 plugin to create a multiple select-input field. Similar to what is shown in the example on page https://select2.github.io/examples.html, I have created my code:

$(document).ready(function() {
{placeholder: "Select tags"},

Now on server side I am using PHP framework(Symfony2) to create the HTML form, which looks roughly like this:

<select id="category_tags___name___tagname" name="category[tags][__name__][tagname][]" required="required" style="width:300px" multiple="" tabindex="-1" class="select2-hidden-accessible">
<option value="1">tag1</option>
<option value="2">tag2</option>
<option value="3" selected="selected">tag3</option>

This works fine, on clicking the field, the available options appear in the dropdown list. But the problem is once I select any of the options, it gets added in the field as a tag, however it still appears in the dropdown list and is not disbaled ie. if I click that option again in the dropdown, it gets deselected.

I want the functionality that, once an option is selected it must appear in the field as a tag, but it should not appear in the dropdown list any longer.

I have searched the web for possible solutions. But found nothing so far.

I am new to Jquery. So all help is appreciated.

Answer Source

According to the docs given in the ref site: https://select2.github.io/examples.html, One way to achieve what you're after would be to use select2:select and select2:unselect events to trigger you custom behavior:

try something like below:

First in your html give each option value an specific ID something like:

   <option value="1" id='specific-1'>tag1</option>
   <option id='specific-2' value="2">tag2</option>
   <option value="3" id='specific-3' selected="selected">tag3</option>

the in your js:

//when select is triggered
$("#category_tags___name___tagname").on("select2:select", function (e) {
   var myID = '#'+e.data.id //getting specific id from event
   $(myID).css('display','none') //hide it using css 

//when unselect is triggered
$("#category_tags___name___tagname").on("select2:unselect", function (e) {
   var myID = '#'+e.data.id //getting specific id from event
   $(myID).css('display','block') //show it using css 

P.S: The above code is untested. But, the logic seems to be right

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download