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.
click the Add button and then select the full name.
click the Add again.
Full name should not be selected in the second <select> or should not be visible.
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>';
}
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.
Related
Is there any feasible way to distinguish newly added options in "select2" from the selected ones, so that i don't have to perform redundant checks to add new values????
When you add a new value, it is selected, so you should be able to add an onchange event:
<select class="form-control" onchange="doSomethingWith(this.value);">
Very rough and ready example, jsfiddle isn't working correctly for me for some reason
https://jsfiddle.net/vd19cwxu/1/
Just set someProperty on all the existing entries
$('#example').select2({
placeholder: 'Select a month'
});
$('#example').val(['JUL', 'AUG']);
$('#example').trigger('change');
$($('#example').select2('data')).each(function(i, val)
{
val.someProp = 1;
});
later when you come to look at the properties you can use filter to just get the new ones
setTimeout(function()
{
const newEntries = $('#example').select2('data').filter(x => !x.someProp);
alert(newEntries.length)
alert(newEntries[0].id)
}, 5000)
I have a select tag like :
<span id="reportProjectSelector">
<span>Reporting Project:</span>
<select id="reportProjectDropdown" onChange="loadChartWithData();" multiple="multiple"></select>
</span>
and
$(function() {
$('#reportProjectDropdown_${widgetId}').multiselect({
includeSelectAllOption: true
});
});
Here I have multiple dropdown chain of other dropdowns which are parents of 'reportProjectDropdown'. For simplicity let's consider just one 'Project'. So now we have 'Projects', on change of which 'Reporting Projects' filter is triggered. Currently the Reporting project filter doesn't change and replace new values (basically null or no values which are replaced by a value like 'No Reporting Projects' in the dropdown)
I have tried removing the previous values but with no luck. Here is the function that I am expecting will do the job.
function setDependentProjects (data, widgetId) {
$('#reportProjectDropdown').find('option').remove().end();
if(jQuery.isEmptyObject(data)) {
let newOption = new Option("No Projects", 0, true, true);
$('#reportProjectDropdown').append(newOption);
} else {
let selected = true;
for(let key in data) {
selected = "${defaultDependentProject}" == data[key];
let newOption = new Option(data[key], key, selected, selected);
$('#reportProjectDropdown').append(newOption);
selected = false;
}
}
loadChartWithData_${widgetId}(); //renders data as per the previous filters
}
Am I missing something or removing the elements incorrectly ?
You need to refresh the jQuery multiselect instance after every change. You can do that by using $('#reportProjectDropdown').multiSelect('refresh');
See also the documentation: jQuery multiselect
I have a Listbox that I need refreshed after a user selects an option in DropdownList.
Image is self explanatory. If one selects Department -> load list of departmetns in Listbox, if one selects Vat Rate refresh/load list of vat rates into the listbox below. (Default department list is loaded on page load). I am currently attempting this with trigger("chosen:updated") and having no luck refreshing listbox. Here is my code for that functionality.
$(function () {
$("#SelectFilter").change(function () {
if (document.getElementById('SelectFilter').value == 1) //dropdownlist
{
//empty listbox
$('#SelectItems').empty();
//append new list to listbox
$.each(data.Departments, function (index, element) {
$('#SelectItems').append('<option value="' + element.Value + '">'
+ element.Text + '</option>');
});
//refresh
$('#SelectItems').trigger("chosen:updated");
}
if (document.getElementById('SelectFilter').value == 2)
{
$('#SelectItems').empty();
$.each(data.VatRates, function (index, element) {
$('#SelectItems').append('<option value="' + element.Value + '">'
+ element.Text + '</option>');
});
$('#SelectItems').trigger("chosen:updated");
}
});
});
Recognising the selected value from the dropdownlist isnt an issue, that works fine. Listbox is currently not getting updated/refresh with new selection. And I cannot figure out were I am going wrong with this.
Try to put all your code for creating the list into a function, and then bind an event on chosing one of the selected items to call this function which generates a new list instead of using .trigger(). If you provide the HTML part as well, I'll post example code soon.
It's not clear to me if you have a problem with recognizing the selected value, or with populating the secondary select tag, or with the initial loading of the data. So I am providing an example of the three steps.
First, to detect the selected value, you need to provide a .change() handler and extract the selected value with .val(). Something similar to this:
$("#SelectFilter").change( function() {
var v = $(this).val();
if (v=="value1") {
} else if (v=="value2") {
} else {
}
});
then each of the changes detected has to refresh the contents of the secondary select tag, something as simple as this...
$("#SelectItems").empty();
['first item','second item','troisième'].forEach( (v,i) =>
$("#SelectItems").append($("<option>").val("item"+i).text(v))
);
}
And finally triggering the initial load should be as simple as triggering a change event
$("#SelectFilter").change();
I have put all the steps together in this fiddle https://jsfiddle.net/mud9u8yL/6/
I have two multi select lists.
On click/select of any item from 1st list, I want to remove the selected item from 1st list and to move the same to 2nd list and vice versa.
I have tried ng-change and ng-click but not getting idea.
Below is my code
1st List
<select style="min-height:200px"
multiple class="form-control"
ng-model="listOneItem"
ng-options="listOneItem.Name for listOneItem in listOneItems track by listOneItem.Name"
ng-change="moveItemsToSecondList();"></select>
2nd List
<select style="min-height:200px"
multiple class="form-control"
ng-model="listTwoItem"
ng-options="listTwoItem.Name for listTwoItem in listTwoItems track by listTwoItem.Name"
ng-change="moveItemsToFirstList();"></select>
Angularjs
$scope.moveItemsToSecondList= function () {
alert(listOneItem[0].Name);
};
$scope.listOneItems= [{
Name: 'Independence Day'
}, {
Name: 'Labor Day'
}, {
Name: 'Thanksgiving Day'
}, {
Name: 'Chrismas Day'
}];
I didn't write functionality to move yet because I am not able to call my methods. i.e. I just put an alert in the method as shown.
Hi I have created jsfiddle demo here
I have added some logic in it that my help you
http://jsfiddle.net/qjcqwhsw/1/
$scope.moveItemsToSecondList= function (items) {
for(var i=0; i<items.length; i++){
var index = $scope.listOneItems.indexOf(items[i]);
$scope.listTwoItems.push(items[i]);
$scope.listOneItems.splice(index, 1);
}
};
I have two multiple select2 boxes, Box1 options are populated dynamically,when i select any option from this select box, it should get added to the new Box2. This scenario is working as required. Problem i am facing is. When i remove any selected item from the Box1, i am able to remove it from Box2. But if that item is selected in Box2 it still remains.
Ex: A,B,C are selected values in Box 1, Box2 gets populated with A,B,C. If i select B,c in Box 2 and if i remove B from Box1. My Box2 items will now be AC. But B,C will still remain selected in Box2.
Can anyone help me in solving this tricky problem.
$("#Box1").on("change", function() {
var box1List = $('#Box1').val();
$('#Box2').empty();
for (var key in box1List) {
var valueField = box1List[key];
var textField = $("#Box1 > option[value='"+valueField+"']").text();
$("#Box2").append($('<option>', {value: valueField, text: textField}));
}
});
$("#Box1").on("select2-removed", function(e) {
console.log("removed val=" + e.val + " choice=" + e.choice.text);
$('#Box2 option[value="'+e.val+'"]').remove();
});
After you alter the child <option> elements of a Select2 <select> element, you should call .change() on it to get it to update its display.
$('#Box2').change();
But in your case, you probably also want to restore the value of the Select2 after you remove and re-add the options.
$("#Box1").on("change", function() {
var val = $('#Box2').select2('val');
$('#Box2').empty();
$.each($('#Box1').select2('data'), function(i, item) {
$("#Box2").append($('<option>', {value: item.id, text: item.text}));
});
$('#Box2').select2('val', val);
});
When you use .select2('val', val) to set the value, you do not need to call .change().
jsfiddle
I have referenced from the post of Pierre de LESPINAY
Glideh. And I tried to apply to my project.
new_data = $.grep($('#my_input').select2('data'), function (value) {
return value['id'] != id_to_remove;
});
$('#my_input').select2('data', new_data);
It worked fine.