Adrian Enriquez
Adrian Enriquez

Reputation: 8413

Multiple <select> using selectize, option removal when already selected

I'm new in using selectize.js, and this is the simplified version of my problem. Please see fiddle below.

Fiddle

What I want is not to select the item when it is already selected.

Ex.

How will I be able to do this?

HTML

<button>Add</button><br/><br/>
<div id="container"></div>

JS

var saveAsOptions = [
        { value: 'full-name', text: 'Full Name' },
        { value: 'first-name', text: 'First Name' },
        { value: 'last-name', text: 'Last Name' }
];

var i = 1;
var $selectSaveAs;

$('button').on('click', function(){
    
    $('#container').append(generateSaveAs(i));
    
    $selectSaveAs = $('#saveAs' + i).selectize({
       options: saveAsOptions, 
       placeholder: '- Fields -'
    });
    
    i++;
});

function generateSaveAs(id){
    return '<select id="saveAs' + id + '"></select>';
}

Upvotes: 0

Views: 5910

Answers (1)

planet260
planet260

Reputation: 1454

So every time you are creating a new drop down you are inserting static values. By analyzing the code I see the selected value always have a class item. So what we can do is create a new array to show in dropdown and filter out the ones already selected. And then we can bind it in drop down.

To filter out you can use filter

saveAsOptionsFiltered = saveAsOptions; //Initialize with your all drop down options
$(".item").each(function(index,element) {
    /*Filter out the already selected ones*/
    saveAsOptionsFiltered = saveAsOptionsFiltered.filter(function (savevalue) {return savevalue.text !== $(element).text() }); 
});

JSFiddle

I have not handled the condition when all are selected and you stop adding more I have just shared the code in which you can filter out the selected ones.

Upvotes: 1

Related Questions