Removing multiple select options and replace with new ones - javascript

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

Related

I am using select2 multiple add....i have a list of categories in select2 dropdown with an option to add new ones

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)

Kendo UI Web - MultiSelect: select an option more than once

I'm currently facing a problem with the Kendo UI MultiSelect widget for selecting an option more than once. For example, in the image below I want to select Schindler's List again after selecting The Dark Knight, but unfortunately the MultiSelect widget behaves more like a set than an ordered list, i.e. repetitive selection is not allowed. Is there actually a proper way to achieve this? Any workarounds?
That's the intended behavior of the multi-select control and there is no simple way to make it do what you want using the available configuration options. Possible workarounds are ...
Creating a custom multi-select widget
Something like this should work (note that I haven't tested this much - it lets you add multiples and keeps the filter intact though):
(function ($) {
var ui = kendo.ui,
MultiSelect = ui.MultiSelect;
var originalRender = MultiSelect.fn._render;
var originalSelected = MultiSelect.fn._selected;
var CustomMultiSelect = MultiSelect.extend({
init: function (element, options) {
var that = this;
MultiSelect.fn.init.call(that, element, options);
},
options: {
name: 'CustomMultiSelect'
},
_select: function (li) {
var that = this,
values = that._values,
dataItem,
idx;
if (!that._allowSelection()) {
return;
}
if (!isNaN(li)) {
idx = li;
} else {
idx = li.data("idx");
}
that.element[0].children[idx].selected = true;
dataItem = that.dataSource.view()[idx];
that.tagList.append(that.tagTemplate(dataItem));
that._dataItems.push(dataItem);
values.push(that._dataValue(dataItem));
that.currentTag(null);
that._placeholder();
if (that._state === "filter") {
that._state = "accept";
}
console.log(this.dataSource.view());
},
_render: function (data) {
// swapping out this._selected keeps filtering functional
this._selected = dummy;
return originalRender.call(this, data);
this._selected = originalSelected;
}
});
function dummy() { return null; }
ui.plugin(CustomMultiSelect);
})(jQuery);
Demo here.
Using a dropdown list
Use a simple dropdown list (or ComboBox) and bind the select event to append to your list (which you have to create manually).
For example:
var mySelectedList = [];
$("#dropdownlist").kendoDropDownList({
select: function (e) {
var item = e.item;
var text = item.text();
// store your selected item in the list
mySelectedList.push({
text: text
});
// update the displayed list
$("#myOrderedList").append("<li>" + text + "</li>");
}
});
Then you could bind clicks on those list elements to remove elements from the list. The disadvantage of that is that it requires more work to make it look "pretty" (you have to create and combine your own HTML, css, images etc.).

filtering only previously unselected <select> options qith JQuery

Previously I asked how to do this and was directed to this:
<script>
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
</script>
(http://www.lessanvaezi.com/filter-select-list-options/)
When I use this filter on the select box it filters both the unselected AND the selected. I'd like it to ONLY filter the unselected because if a user wants to ammend the selections and filters again, the previously selected items go away - unless they meet the filter criteria.
I'm not that good at JavaScript or JQuery and can't understand how I might tell the above script to ignore options that are ":selected" but filter all else.
Here's a jfiddle if it helps: http://jsfiddle.net/UmKXy/ I'd like option one and two to remain selected and in the list when user begins to type.
Thanks for help!
The solution you had would not work with selected elements because he created an array of options at the start and then matched those options against the regex(Without regards to what is actually selected). I've used spans to hide options in the past and created an example for you to see how it works. Here is the link : http://jsfiddle.net/rD6wv/
Here is the code
$(function() {
$("#filterByText").bind('keyup',function(){
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$("#filez").find('option').each(function(){
if(!$(this).is(':selected')){
if($(this).val().match(regex) === null) {
$(this).wrap('<span>');
}else if($(this).parent().is('span')){
$(this).parent().replaceWith($(this));
}
}
});
});
});
You simply need to loop through all the options of the select when you type in the textbox.
You then check if it is selected, if it is you do nothing, else you check if it matches the search filter, if it does you wrap it in a span, making it invisible, else it means you need to see it, so you check if it is already wrapped in a span, and in that case you replace it with the option so you can see it again.
to selected the non selected options, use this:
$('option:not[selected]') or $('#myselect > option:not[selected]')
to remove them, use this:
$('option:not[selected]').remove();
in css, :not filters for opposite of what comes in the curved brackets.
and [] is attribute selector.
so :not[selected] means: does not have an attribute whose key is "selected"

Select2 Dropdown Dynamically Add, Remove and Refresh Items from

This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)
i have a select2 which gets data from a ajax call.
<input id="valueg" type="hidden" style="width: 300px;" data-placeholder="Select a Conference" />
$("#valueg").select2({
data: conferences,
allowClear: true,
initSelection: function (element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
}
}).on("change", function (e) {
// show data in separate div when item is selected
});
Can some one provide a clear method how to delete and add an item from the Select2.
For example:
I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.
I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.
From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:
$('#valueg').select2('val', 'YOUR_VALUE');
In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:
var el = $('select[name="type"]', '#details-form');
var temp = el.select2('val'); // save current value
temp.push(NEW_VALUE); // append new one
var newOptions = '<option value="1">1</option><option value="2">2</option>';
el.select2('destroy').html(newOptions ).select2().select2('val', temp);
I did it this way:
var $select2 = $('#valueg').select2(); // getting the select2
var item = 'xyz'; // item to be added
$select2.val(function(i, val) { // val can take function as parameter
val = val || []; // if value is null init val as an array
val.push(item); // add the new item
return val;
}).trigger("change"); //refresh
Hope that helps
I had the same issue. This is how i solved it
This has nothing to do with select2, manipulating the itself seems to work for me
$("#lstService").empty();
for(var i=0;i<data.length;i++){
$("#lstService").append('<option value="'+data[i].service_id+'">'+data[i].service_name+'</option>');
}
In my case, the key thing to add after manipulating the underlying select is:
$selectlist.trigger("change"); //$selectlist is the underlying select element.
Select2 works around the change event on a select, so calling "change" updates the option displayed in the select 2.
It is too late... but this is my solution for people that still have this problem:
html = "";
jQuery("#select_2 option").each(function()
{
html += '<option value="'+jQuery(this).attr("value")+'">'+jQuery(this).text()+'</option>';
});
html += '<option value="NEWVALUE">NEW OPTION</option>';
jQuery("#select_2").html(html);

jquery, javascript, update dropdown list options upon focus but retain selected value

Brain not working right now. Someone help me fill in the blanks here.
Need to select the currently selected value, repopulate the options, and then select the previous selection if it's still in the list.
To make it easier, the new value and previously selected value will have the same name attribute assuming it's still in the list after updating, and names will always be unique for the list of options.
//assume Options is a globally defined var for this example with format:
// [{"display":"something", "value": "something's value"}, etc.. ]
function LazyLoadOptionsIntoSelect($select, options)
{
//get current option
//repopulate options
$select.html("");
$("<option>").text("--Select a File--")
.appendTo($select);
$.each(options, function()
{
var item = this;
$("<option>").attr("name", function () { return item.display; })
.val(function () { return item.value; })
.text(item.display)
.appendTo($select);
});
//select previously selected option if still in list
}
$(".lazyloadedselect", "#context").live("focus", function()
{
LazyLoadOptionsIntoSelect($(this), Options);
});
EDIT: mistake in my code, unrelated to the problem, but still wrong
If the option retains the same value attribute:
//get current option
var theOption = $select.val();
And later...
//select previously selected option if still in list
$select.val(theOption);
EDIT
You'll need to fix an error in your population code because none of those options actually have value attributes, which is probably why you can't properly set the value of the select:
$.each(options, function(index, item) {
$("<option>")
.attr("value", item.display)
.text(item.display)
.appendTo($select);
});
Please note name is not a standard attribute for an option element.

Categories

Resources