Order of Select2 selection based on array of items - javascript

I'm trying to set the order of selected items in Select2 based on an array.
A simple solution has already been proposed to append items in the order with which they are clicked in the dropdown menu (see 2rba's answer on 2017-10-26 in this discussion):
$("#selectCriteria").on("select2:select", function (evt) {
var element = evt.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
});
What I'm trying to do is mimick this behavior, but when passing an array of the selected items instead of manually clicking them in the list. I tried the following command:
displayed_items = ["b", "c", "a"];
$('#selectCriteria').val(displayed_items).trigger('change');
But the order isn't preserved. I tried looping the command with one element at a time, but each new call overwrites the previous element:
$('#selectCriteria').val("b").trigger('change');
$('#selectCriteria').val("c").trigger('change');
$('#selectCriteria').val("a").trigger('change');
I see two possible solutions to this, but lack the background to make them work:
How should the iteration above be adapted to not overwrite the previously added
value?
How could I incorporate the approach shown in this
fiddle (from vol7ron's posts on github) which does pretty
much what I'm asking (i.e. toggling on/off the
.data('preserved-order',selected))? As it is using JSX I'm
not sure how I could reuse that script in my plain JS/jQuery script.

here you go
EDIT:
this is not the prettiest solution, but it gets the job done.
you would have to call initSelect function that takes an array of values as a parameter. i left some comments in the code.
displayed_items = $('#selected_items').val().split(',');
function selectItem(target, id) { // refactored this a bit, don't pay attention to this being a function
var option = $(target).children('[value='+id+']');
option.detach();
$(target).append(option).change();
}
function customPreSelect() {
let items = $('#selected_items').val().split(',');
$("select").val('').change();
initSelect(items);
}
function initSelect(items) { // pre-select items
items.forEach(item => { // iterate through array of items that need to be pre-selected
let value = $('select option[value='+item+']').text(); // get items inner text
$('select option[value='+item+']').remove(); // remove current item from DOM
$('select').append(new Option(value, item, true, true)); // append it, making it selected by default
});
}
$('select').select2();
$('select').on('select2:select', function(e){
selectItem(e.target, e.params.data.id);
});
initSelect(displayed_items); // call init
select {
width: 50%;
}
.container {
display: flex;
flex-direction: column;
}
.control-group {
padding-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<div class="container">
<p>Provide comma separated items to be pre selected and click the button</p>
<div class="control-group">
<input id="selected_items" value="b,c,a"/>
<button onclick="customPreSelect()">Init</button>
</div>
<select multiple="multiple">
<option value="a">A</option>
<option value="b" >B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
</div>

This preserves attributes of the select2 options (e.g. titles used for tooltips):
function initSelect(items) {
items.forEach(item => {
var option = $('#selectCriteria').children('[value="' + item + '"]');
option[0].selected = true;
option.detach();
$('#selectCriteria').append(option).change();
})
}

Related

Hide Dropdown List Value, when another dropdown value selected Javascript

so, i want to hide "Overtime AC" Value when i choose Balikpapan Office.
This is my code, still not working
var ddlLoc = $("[id$='_ddl_OfficeLocationosf']");
var ddlReqFor = $("[id$='_ddl_RequestForosf']");
ddlLoc.change(function() {
if(ddlLoc.find("option[value='Balikpapan Office']") == true) {
ddlReqFor.find("option[value='Overtime AC']").parent().parent().hide();
} else {
ddlReqFor.find("option[value='Overtime AC']").parent().parent().show();
}
});
Why use parent().parent() of the option you want to hide?
Do they have a common parent?
$("[id$='_ddl_OfficeLocationosf']").on("change",function() {
$(this)
.closest(".commonContainerClass")
.find("[id$='_ddl_RequestForosf'] option[value='Overtime AC']")
.toggle(this.value === 'Balikpapan Office')
})
Native JavaScript Solution
This is a native JavaScript solution to compliment #mplungjan jQuery solution. The solutions work differently, but both solve the problem of creating a cascading select.
Add an event handler to capture the office name and copy it to data-office attribute on the second select:
_ddl_OfficeLocationosf.addEventListener('change', function() {
_ddl_RequestForosf.dataset.office = this.value;
});
Then we add a css rule that selectively hides options that match the selected offices. This is done by adding a data-exclude attribute with a list of office names where the options should be hidden. Note that we're using a *= match so that we don't need to use full names. In this case we are only hiding one option, but it would be easy to create custom lists for each office.
#_ddl_RequestForosf[data-office*=Balik] option[data-exclude*=Balik] {
display: none;
}
And the markup
<option data-exclude="Balikpapan">Overtime AC</option>
Snippet
The snippet includes some additional code to handle loading and switching offices. See comments for details.
_ddl_OfficeLocationosf.addEventListener('change', function() {
_ddl_RequestForosf.dataset.office = this.value;
// optional -clear previous selection when not an option for current office
let option = _ddl_RequestForosf.querySelector('option:checked');
if (option && getComputedStyle(option).display === 'none') {
_ddl_RequestForosf.value = "";
}
});
// optional - update the control on page load
document.addEventListener('DOMContentLoaded', function() {
_ddl_OfficeLocationosf.dispatchEvent(new Event('change'));
});
body {
font-family: sans-serif;
}
#_ddl_RequestForosf[data-office*=Balik] option[data-exclude*=Balik] {
display: none;
}
<label>Office
<select id="_ddl_OfficeLocationosf">
<option>Balikpapan Office</option>
<option>Brunei Office</option>
<option>Makassar Office</option>
</select>
</label>
<label>Request:
<select id="_ddl_RequestForosf">
<option>Stationary</option>
<option>Business Card</option>
<option>Stamp</option>
<option data-exclude="Balikpapan">Overtime AC</option>
<option>Condolence Bouquet</option>
<option>Fogging for Employee House</option>
<option>Foldable Box</option>
<option>Others</option>
</select>
</label>

How to create a dropdown that changes the background of your website using Javascript?

I'm working on an assignment that requires the background of the website to change based on the selected dropdown option. ie. If 'NYC' is selected, the background changes to a photo of NYC, where the relative URL of the image is already in CSS.
I am required to add the city options using an array with values 'NYC, SF, LA, ATX, SYD' using a 'for loop' in JS, instead of adding it directly to the HTML. I am also asked to specifically incorporate $.append(), $.attr(), $.val(), $.change() and the if/else if statement in the JS code.
I've tried writing the code from scratch along with help from other sources but the pre-written codes don't work with my specific requirements. I understand the HTML and CSS but I'm still very new to Javascript and JQuery. Enough to know it's wrong. I definitely have not gotten the right code for the 'for loop' or the dropdown menu thus far.
Here is the HTML:
<body>
<header>
<div class="title">
<h1>CitiPix</h1>
<p>Your Cities, Your Pix</p>
</div>
</header>
<div class="container">
<form>
<select id="city-type">
<option>Select a City</option>
</select>
</form>
</div>
</body>
This is the JS I have so far:
$(document).ready(function(){
$('.container').click(function(event){
var cityName = ['NYC, SF, LA, ATX, SYD'];
$("#city-type").append(var cityName);
cityBackground(city);
if (!event.target.matches('#submit-btn')) {
var dropdowns = document.getElementsByClassName('city-type');
var i;
for (i = 0; i < container.length; i++) {
}}}
$('select').change(displayVals);
displayVals();
function displayVals() {
var cityName = $( "#city-type" ).val();
function cityBackground(citytype){
if (citytype === 'NYC')
{
$('body').attr('class', 'nyc');
}
else if (citytype === 'SF')
{
$('body').attr('class', 'sf');
}
else if (citytype === 'LA')
{
$('body').attr('class', 'la');
}
else if (citytype === 'ATX')
{
$('body').attr('class', 'austin');
}
else if (citytype === 'SYD')
{
$('body').attr('class', 'sydney');
}
}
}
The dropdown menu is not showing, it just shows the "Select a City" text and the whole dropdown code is not running. The .change and .val requirements are also confusing as to where its suppose to fit in the code.
Cycling through a loop
There's actually nothing wrong with your loop, you just aren't doing anything within the loop. You need to add to the select element from within the loop you have defined.
// Cycle through the array
for (i = 0; i < cityName.length; i++) {
// Code to be repeated for each element goes here
}
Adding to a select
Check this answer for ways of adding options to a select:
Adding options to a <select> using jQuery?
In the example below I have used the following line, but there may be some issues in IE that you will need to explore, or use the alternative that the accepted answer suggests.
$("select").append(new Option("text", "value"));
Gathering the select value
You can get the value of a select using .val() - i.e. $("#select").val() will provide the value of the chosen option. You're doing this correctly already.
Manipulating the classes
You can add a class to an element using .addClass("classname");
You can reset all classes by setting the class attribute to a blank string - i.e. .attr("class", ""), or assign classes by providing a second argument instead of an empty string.
Your use of .attr("class", "NYC") is actually allowing you to combine these steps into one command. You're doing this correctly already.
Demo
// Create array of cities
var cityName = ["NYC", "SF"];
// Cycle through the array
for (i = 0; i < cityName.length; i++) {
// Add options to the select
$("#city-type").append(new Option(cityName[i], cityName[i]));
}
// Add change event to select
$("#city-type").change(function() {
// Clear classes on the body and assign new value
$("body").attr("class", $(this).val() );
});
.NYC {
background: blue;
}
.SF {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header>
<div class="title">
<h1>CitiPix</h1>
<p>Your Cities, Your Pix</p>
</div>
</header>
<div class="container">
<form>
<select id="city-type">
<option>Select a City</option>
</select>
</form>
</div>
</body>
You have several syntax errors in your Javascript, many braces and parentheses aren't closed, some functions are being called before they are declared.
This is a partial solution for your problem: https://jsfiddle.net/jkpdLuho/1/
$(document).ready(function() {
var places = ['NYC', 'SYD']
for (i = 0; i < places.length; i++) {
$('select').append('<option value="' + places[i] + '">' + places[i] + '</option>')
}
$('select').on('change', function() {
$('body').attr("class", this.value)
})
})
<html>
<header>
<div class="title">
<h1>CitiPix</h1>
<p>Your Cities, Your Pix</p>
</div>
</header>
<body>
<form>
<select id="city-type">
<option>Select a City</option>
</select>
</form>
</body>
</html>
.NYC {
background: yellow;
}
.SYD {
background: pink;
}
I'd recommend using a code editor that correctly indents your code for you (such as using AtomBeautify if you're using Atom), it will make it easier to notice any unclosed statements. When it comes to learning jQuery, it's also good to play around using the browser's dev console to see what effects jQuery commands have on the DOM. You'll for example see that you need to write out the entire HTML element if you do $('select').append('<option>Name</option>').

javascript hide/show items in dropdown list

I started studying javascripting and was wondering if anyone know how to hide values in dropdown list for html?
For example: a dropdwon list with values
Select One
Item1
Item2
Item3
Item4
Item5
I wanna hide the Item 4 and 5, like this and show it when "Show... " is clicked.
Select One
Item1
Item2
Item3
Show 2 more items (Item 4 and 5 hidden)
Is that possible? Below is a piece of code i already started.
var css = select;
var markers = cluster.getMarkers();
var markersLength = markers.length;
var nextOption = new Option("Select One");
css.add(nextOption, 0);
for(var i = 0; i < markersLength; i++) {
nextOption = new Option(markers[i].title);
try {
css.add(nextOption, -1);
} catch (e) {
css.add(nextOption, null);
}
}
You want a generic solution, so tag the more option and the hidden items with classes.
It turns out you cannot consistently style-out options in a select across browsers, so you need to dynamically alter the list options: Refer to this question: How to hide a <option> in a <select> menu with CSS?
Final solution (append elements from another hidden select):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/93D3h/12/
HTML:
Select One
<select class="hidden">
<option>Item4</option>
<option>Item5</option>
<option>Item6</option>
<option>Item7</option>
<select>
<select>
<option>Item1</option>
<option>Item2</option>
<option>Item3</option>
<option class="more">More</option>
</select>
jQuery:
$('select').change(function(){
var $select = $(this);
if ($select.val() == "More"){
$('.more').remove();
$select.append($('.hidden').children());
}
});
Previous info:
Then on then select change event you hide the more option and show the hidden elements:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/93D3h/2/
$('select').change(function(){
var $select = $(this);
if ($select.val() == "More"){
$('.more').hide().prevAll('.hidden').show();
}
});
There appears to be a weird bug in selects as the last item is always visible (even when styled out!). I added a blank entry to fix this for now. This is also why I did not place the hidden items after the more as the last one always shows (what a strange bug - have asked that as a new question: Why is last select option always shown, even when styled out).
You will also want to clear the selected value of "More" as that will no longer exist.
e.g. http://jsfiddle.net/TrueBlueAussie/93D3h/3/
$('select').change(function () {
var $select = $(this);
if ($select.val() == "More") {
$('.more').hide().prevAll('.hidden').show();
$select.val('');
}
});
Followup:
Based on my related question, I was pointed to this one: How to hide a <option> in a <select> menu with CSS? Apparently you cannot style out select options consistently, so adding the items to the list dynamically would be the ideal solution.
Here's my solution:
Html
<select id="test">
<option value="1">Select One</option>
<option value="2">Item 1</option>
<option value="3">Item 2</option>
<option value="4">Item 3</option>
<option value="5">Select Two</option>
<option value="6">Item 4</option>
<option value="7">Item 5</option>
</select>
Script
var array1 = ["1","6","7"];
var array2 = ["1","2","3","4"];
var arrayAll = ["1","2","3","4","5","6","7"];
function hideOptions(array) {
for (var i = 0; i < array.length; i++) {
$('#test option[value="' + array[i] + '"]').hide();
}
}
function showOptions(array) {
for (var i = 0; i < array.length; i++) {
$('#test option[value="' + array[i] + '"]').show();
}
}
$("#test").change(function(){
if($("#test").val()=="5"){
hideOptions(array2);
showOptions(array1);
}
if($("#test").val()=="1"){
hideOptions(array1);
showOptions(array2);
}
});
hideOptions(array1);
here's the fiddle
What about something like:
<head>
<script type="text/javascript">
function makeDynamicOption(target, threshold, messageMore, messageLess) {
var allOptions = collectOptions();
target.addEventListener("change", updateOptions, false); // Use your own event manager
showOptions(threshold);
addMessage(messageMore);
// ---
function collectOptions() {
var options = [];
for(var ii=0; ii<target.options.length; ii++) {
options.push(target.options[ii]);
}
return options;
}
function updateOptions() {
var selectedText = this.options[this.selectedIndex].text;
if (selectedText == messageMore) {
showOptions(allOptions.length);
addMessage(messageLess);
} else if (selectedText == messageLess) {
showOptions(threshold);
addMessage(messageMore);
}
}
function showOptions(upToIndex) {
removeOptions();
for (var ii=0; ii<upToIndex; ii++) {
target.options[ii] = allOptions[ii];
}
}
function removeOptions() {
while(target.options.length > 0) {
target.removeChild(target.options[0]);
}
}
function addMessage(message) {
target.options[target.options.length] = new Option(message, "");
}
}
</script>
</head>
<body>
<select id="foo">
<option value="value1">item1</option>
<option value="value2">item2</option>
<option value="value3">item3</option>
<option value="value4">item4</option>
<option value="value5">item5</option>
</select>
<script type="text/javascript">
makeDynamicOption(
document.getElementById("foo"),
3,
"More...",
"Less..."
);
</script>
</body>
This design separates the lib part (to be linked in the HEAD as an external script) from the activation part. It also lets you inject localized text while generating the view, and preserve existing options in case you have other scripts interacting with them. Note that you should still use your own event manager, and not addEventListener directly as shown in the script, for better cross-browser support.
EDIT: here's how the scripts works:
You call the makeDynamicOptions() function on the select object you want to augment, passing the number of options you want to display, as well as messages to expand/collapse other options. The messages can be written by the view manager, i.e. it could be easily localized if needed.
The first initialization step sees that all original options be collected, so that they can be added back when the user wants to expand the select. Note that we collect the objects themselves, and not only their value/text property values, as other scripts could reference these objects.
The second initialization step registers a change handler on the select, so as to trigger the update on the options list. The script uses addEventListener, but one should substitute one's own event management mechanism, for better cross-browser support.
The last initialization step collapses the select in the intended start position.
The rest is pretty straightforward. Once the user selects an option, the script decides whether the list of options should be repopulated, by analyzing the text of the selected option, and comparing it to the provided expand/collapse labels. If options are to be redrawn, then the script removes all options, adds the expected ones, then adds the new expand/collapse message.
HTH.

Using JavaScript and JQuery, How Can I Maintain the Selected State of a Dynamically-Updated HTML Select Element?

I have a form UI whereby several sections require duplicate HTML select list to be updated dynamically from a single, dynamically-updatable select list.
The dynamically-updatable list works just fine, in that new options can be added and removed on-the-fly. I can then get this update to propagate through each of the duplicate lists using JQuery .find(). I have even added a bit of logic to maintain the currently selected index of the original select list.
What I'm not able to do is maintain the selected state of each of the duplicate select lists as new options are added and removed from the original select list. As each update to the original select list iterates through each duplicate select list, they lose their currently selected option index.
Here is an example of my conundrum--*EDIT--I would encourage you to try and execute the code I've provided below and apply your theories before suggesting a solution, as none of the suggestions so far have worked. I believe you will find this problem a good deal trickier than you might assume at first:
<form>
<div id="duplicates">
<!--// I need for each of these duplicates to maintain their currently selected option index as the original updates dynamically //-->
<select>
</select>
<select>
</select>
<select>
</select>
</div>
<div>
<input type="button" value="add/copy" onclick="var original_select = document.getElementById('original'); var new_option = document.createElement('option'); new_option.text = 'Option #' + original_select.length; new_option.value = new_option.text; document.getElementById('original').add(new_option); original_select.options[original_select.options.length-1].selected = 'selected'; updateDuplicates();" />
<input type="button" value="remove" onclick="var original_select = document.getElementById('original'); var current_selected = original_select.selectedIndex; original_select.remove(original_select[current_selected]); if(original_select.options.length){original_select.options[current_selected < original_select.options.length?current_selected:current_selected - 1].selected = 'selected';} updateDuplicates();" />
<select id="original">
</select>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function updateDuplicates(){
$("#duplicates").find("select").html($("#original").html());
}
</script>
</form>
It is important to note that the duplicate HTML select lists should remain somewhat arbitrary, if at all possible (i.e.; no ID's) as this method needs to apply generically to other dynamically-created select lists throughout the document.
Thanks in advance!
Still not 100% sure what you're asking but it seems like this should do what you're looking for and is a few less lines of code.
(function () {
function updateDuplicates() {
$("#duplicates").find("select").html($("#original").html());
$('#duplicates select').each(function () {
var lastSelectedValue = $(this).data('lastSelectedValue');
$(this).val(lastSelectedValue || $(this).val());
});
}
$(document).ready(function () {
$('button:contains(remove)').bind('click', function (e) {
e.preventDefault();
var original_select = document.getElementById('original'),
current_selected = original_select.selectedIndex;
original_select.remove(original_select[current_selected]);
if (original_select.options.length) {
original_select.options[current_selected < original_select.options.length ? current_selected : current_selected - 1].selected = 'selected';
}
updateDuplicates();
});
$('button:contains(add/copy)').bind('click', function (e) {
e.preventDefault();
var original_select = document.getElementById('original'),
new_option = document.createElement('option');
new_option.text = 'Option #' + original_select.length;
new_option.value = new_option.text;
document.getElementById('original').add(new_option);
original_select.options[original_select.options.length - 1].selected = 'selected';
updateDuplicates();
});
$('#duplicates select').bind('change', function () {
$(this).data('lastSelectedValue', $(this).val());
});
} ());
} ());
EDIT: I changed your markup to be
<button>add/copy</button>
<button>remove</button>
just set the currently selected item/value of select to some variable, then do your operation,
finally reselect the value to the select.
Okay, I think I have a workable approach to a solution, if not a clumsy one. The tricky part isn't adding a value to the original list, because the added option is always at the end of the list. The problem comes in removing a select option because doing so changes the index of the currently selectedIndex. I've tested using Google Chrome on a Mac with no errors. I have commented the code to demonstrate how I approached my solution:
<form>
<div id="duplicates">
<!--// Each of these select lists should maintain their currently selected index //-->
<select>
</select>
<select>
</select>
<select>
</select>
</div>
<div>
<!--// Using a generic function to capture each event //-->
<input type="button" value="add/copy" onClick="updateDuplicates('add');" />
<input type="button" value="remove" onClick="updateDuplicates('remove');" />
<select id="original">
</select>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function updateDuplicates(editMode){
///* Capture the selectedIndex of each select list and store that value in an Array *///
var original_select = document.getElementById('original');
var current_selected = new Array();
$("#duplicates").find("select").each(function(index, element) {
current_selected[index] = element.selectedIndex;
});
switch(editMode){
case "add":
var new_option = document.createElement('option');
new_option.text = 'Option #' + original_select.length;
new_option.value = new_option.text;
original_select.add(new_option);
original_select.options[original_select.options.length-1].selected = 'selected';
///* Traverse each select element and copy the original into it, then set the defaultSelected attribute for each *///
$("#duplicates").find("select").each(function(index, element){
$(element).html($("#original").html());
///* Retrieve the currently selected state stored in the array from before, making sure it is a non -1 value, then set the defaultSelected attribute of the currently indexed element... *///
if(current_selected[index] > -1){
element.options[current_selected[index]].defaultSelected = true;
}
});
break;
case "remove":
var current_index = original_select.selectedIndex;
original_select.remove(original_select[current_index]);
///* Thou shalt not remove from thine empty list *///
if(original_select.options.length){
original_select.options[current_index > 0?current_index - 1:0].selected = 'selected';
}
///* Traverse each select element and copy the original into it... *///
$("#duplicates").find("select").each(function(index, element){
$(element).html($("#original").html());
///* Avoid operating on empty lists... *///
if(original_select.options.length){
///* Retrieve the currently selected state stored in the array from before, making sure it is a non -1 value... *///
if(current_selected[index] > -1){
///* If the stored index state is less or equal to the currently selected index of the original... *///
if(current_selected[index] <= current_index){
element.options[current_selected[index]].defaultSelected = true;
///* ...otherwise, the stored index state must be greater than the currently selected index of the original, and therefore we want to select the index after the stored state *///
}else{
element.options[current_selected[index] - 1].defaultSelected = true;
}
}
}
});
}
}
</script>
</form>
There is plenty of room to modify my code so that options can be inserted after the currently selectedIndex rather than appended to the end of the original select list. Theoretically, a multi-select list/menu should work as well. Have at thee.
I'm sure one of the geniuses here will be able to do this same thing with cleaner, prettier code than mine. Thanks to everyone who reviewed and commented on my original question! Cheers.
If you can reset a little, I think that the problem is you are setting your select list's HTML to another list's HTML. The browser probably doesn't try to preserve the currently selected item if all the of underlying html is being changed.
So, I think what you might try doing is explicitly adding the option elements to the target lists.
Try this jsfiddle. If you select an item other than the default first item and click "add", notice that the selected item is maintained. So you need to be a little more surgical in your managing of the target list items.
Maybe that'll help or maybe I missed the point.

Problem with multiple select removing more than 1 option

There seems to be a problem with the JS Code for Opera browsers, as it only removes the last option tag that is selected within a multiple select tag, can someone please help me.
Here is the HTML for this:
<select id="actions_list" name="layouts" multiple style="height: 128px; width: 300px;">
<option value="forum">forum</option>
<option value="collapse">collapse</option>
<option value="[topic]">[topic]</option>
<option value="[board]">[board]</option>
</select>
Of course it's within a form tag, but there's a ton more code involved with this form, but here is the relevant info for this.
Here is the JS that should handle this, but only removes the last selected option in Opera, not sure about other browsers, but it really needs to remove all selected options, not just the last selected option...
var action_list = document.getElementById("actions_list");
var i = action_list.options.length;
while(i--)
{
if (action_list.options[i].selected)
{
action_list.remove(i);
}
}
What is wrong with this? I can't figure it out one bit.
It's easiest to do this with jQuery but it you want to do this using plain Javascript you can.
The problem you are experiencing is that when you remove an item from the options list in Opera it deselects all the selected items, so only the first is removed. A workaround is to first remember which items were selected before removing any.
var action_list = document.getElementById("actions_list");
// Remember selected items.
var is_selected = [];
for (var i = 0; i < action_list.options.length; ++i)
{
is_selected[i] = action_list.options[i].selected;
}
// Remove selected items.
i = action_list.options.length;
while (i--)
{
if (is_selected[i])
{
action_list.remove(i);
}
}
You can do it much easier using jQuery:
$('#actions_list option:selected').remove()
$.each($('[name="alltags"] option:selected'), function( index, value ) {
$(this).remove();
});
try this instead to remove multiple selection
Removing multiple options from select based on condition:
while(SelectBox.length > 1){
if(SelectBox[SelectBox.length -1].text != "YourCondition"){
SelectBox.remove(SelectBox.length -1);
}
}

Categories