How to hide a <option> in a <select> menu with CSS? - javascript

I've realized that Chrome, it seems, will not allow me to hide <option> in a <select>. Firefox will.
I need to hide the <option>s that match a search criteria. In the Chrome web tools I can see that they are correctly being set to display: none; by my JavaScript, but once then <select> menu is clicked they are shown.
How can I make these <option>s that match my search criteria NOT show when the menu is clicked?

For HTML5, you can use the 'hidden' attribute.
<option hidden>Hidden option</option>
It is not supported by IE < 11. But if you need only to hide a few elements, maybe it would be better to just set the hidden attribute in combination with disabled in comparison to adding/removing elements or doing not semantically correct constructions.
<select>
<option>Option1</option>
<option>Option2</option>
<option hidden>Hidden Option</option>
</select>
Reference.

You have to implement two methods for hiding. display: none works for FF, but not Chrome or IE. So the second method is wrapping the <option> in a <span> with display: none. FF won't do it (technically invalid HTML, per the spec) but Chrome and IE will and it will hide the option.
EDIT: Oh yeah, I already implemented this in jQuery:
jQuery.fn.toggleOption = function( show ) {
jQuery( this ).toggle( show );
if( show ) {
if( jQuery( this ).parent( 'span.toggleOption' ).length )
jQuery( this ).unwrap( );
} else {
if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
}
};
EDIT 2: Here's how you would use this function:
jQuery(selector).toggleOption(true); // show option
jQuery(selector).toggleOption(false); // hide option
EDIT 3: Added extra check suggested by #user1521986

I would suggest that you do not use the solutions that use a <span> wrapper because it isn't valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you'll only need these 3 functions:
The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.
function setOriginalSelect ($select) {
if ($select.data("originalHTML") == undefined) {
$select.data("originalHTML", $select.html());
} // If it's already there, don't re-set it
}
This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.
function removeOptions ($select, $options) {
setOriginalSelect($select);
$options.remove();
}
The last function can be used whenever you want to "reset" back to all the original options.
function restoreOptions ($select) {
var ogHTML = $select.data("originalHTML");
if (ogHTML != undefined) {
$select.html(ogHTML);
}
}
Note that all these functions expect that you're passing in jQuery elements. For example:
// in your search function...
var $s = $('select.someClass');
var $optionsThatDontMatchYourSearch= $s.find('options.someOtherClass');
restoreOptions($s); // Make sure you're working with a full deck
removeOptions($s, $optionsThatDontMatchYourSearch); // remove options not needed
Here is a working example: http://jsfiddle.net/9CYjy/23/

Ryan P's answer should be changed to:
jQuery.fn.toggleOption = function (show) {
$(this).toggle(show);
if (show) {
if ($(this).parent('span.toggleOption').length)
$(this).unwrap();
} else {
**if ($(this).parent('span.toggleOption').length==0)**
$(this).wrap('<span class="toggleOption" style="display: none;" />');
}
};
Otherwise it gets wrapped in too many tags

Select inputs are tricky in this way. What about disabling it instead, this will work cross-browser:
$('select').children(':nth-child(even)').prop('disabled', true);
This will disable every-other <option> element, but you can select which ever one you want.
Here is a demo: http://jsfiddle.net/jYWrH/
Note: If you want to remove the disabled property of an element you can use .removeProp('disabled').
Update
You could save the <option> elements you want to hide in hidden select element:
$('#visible').on('change', function () {
$(this).children().eq(this.selectedIndex).appendTo('#hidden');
});
You can then add the <option> elements back to the original select element:
$('#hidden').children().appendTo('#visible');
In these two examples it's expected that the visible select element has the id of visible and the hidden select element has the id of hidden.
Here is a demo: http://jsfiddle.net/jYWrH/1/
Note that .on() is new in jQuery 1.7 and in the usage for this answer is the same as .bind(): http://api.jquery.com/on

The toggleOption function is not perfect and introduced nasty bugs in my application. jQuery will get confused with .val() and .arraySerialize()
Try to select options 4 and 5 to see what I mean:
<select id="t">
<option value="v1">options 1</option>
<option value="v2">options 2</option>
<option value="v3" id="o3">options 3</option>
<option value="v4">options 4</option>
<option value="v5">options 5</option>
</select>
<script>
jQuery.fn.toggleOption = function( show ) {
jQuery( this ).toggle( show );
if( show ) {
if( jQuery( this ).parent( 'span.toggleOption' ).length )
jQuery( this ).unwrap( );
} else {
jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
}
};
$("#o3").toggleOption(false);
$("#t").change(function(e) {
if($(this).val() != this.value) {
console.log("Error values not equal", this.value, $(this).val());
}
});
</script>

Simple answer: You can't. Form elements have very limited styling capabilities.
The best alternative would be to set disabled=true on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.
Alternatively, if you can, completely remove the option element.

// Simplest way
var originalContent = $('select').html();
$('select').change(function() {
$('select').html(originalContent); //Restore Original Content
$('select option[myfilter=1]').remove(); // Filter my options
});

Since you're already using JS, you could create a hidden SELECT element on the page, and for each item you are trying to hide in that list, move it to the hidden list. This way, they can be easily restored.
I don't know a way offhand of doing it in pure CSS... I would have thought that the display:none trick would have worked.

You should remove them from the <select> using JavaScript. That is the only guaranteed way to make them go away.

!!! WARNING !!!
Replace the second "IF" by "WHILE" or doesn't work !
jQuery.fn.toggleOption = function( show ) {
jQuery( this ).toggle( show );
if( show ) {
while( jQuery( this ).parent( 'span.toggleOption' ).length )
jQuery( this ).unwrap( );
} else {
jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
}
};

this one seems to work for me in chrome
$("#selectid span option").unwrap();
$("#selectid option:not([filterattr=filtervalue])").wrap('<span/>');

Simply use option[value=your-value]{display:none;}
This works fine in Chrome, at least in 2022, as well as in safari and FF.

Modern solution is simply apply CSS hidden like:
<option value="" style="display:none;">Select Item</option>
Or with a class
<option value="" class="hidden">Please select</option>
Note in class case, add css like
.hidden {
display: none;
}

Late to the game, but most of these seem quite complicated.
Here's how I did it:
var originalSelect = $('#select-2').html();
// filter select-2 on select-1 change
$('#select-1').change(function (e) {
var selected = $(this).val();
// reset select ready for filtering
$('#select-2').html(originalCourseSelect);
if (selected) {
// filter
$('#select-2 option').not('.t' + selected).remove();
}
});
markup of select-1:
<select id='select-1'>
<option value=''>Please select</option>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
markup of select-2:
<select id='select-2'>
<option class='t1'>One</option>
<option class='t2'>Two</option>
<option>Always visible</option>
</select>

Simply, this can achieved by HTML too.
<select>
<option value="" disabled selected hidden>Please Choose</option>
<option value="0">hii</option>
<option value="1">hello</option>
</select>

2022 Answer Summary And Cross-Browser Solution
Currently, these methods do not work on Safari:
visibility: hidden
display: block
hidden attribute
So none of proposed solutions here using these methods works on Safari, so they can not be accepted.
Solution
The solution is to keep special options in an array, and hide/restore them on-demand. For example to show/hide day selection based on year/month selection:
When you initialize your component:
const tailDayOptions = [];
const saveTailDayOptions = () => {
const daySelector = document.querySelector('#daySelector');
for (let day = 29; day <= 31; day++) {
tailDayOptions[day - 1] = daySelector.querySelector(`option[value='${day - 1}']`);
}
}
When a user changes year or month:
for (let day = 29; day <= 31; day++) {
if (day <= daysInMonth) {
daySelector.appendChild(tailDayOptions[day - 1])
} else {
const dayOption = daySelector.querySelector(`option[value='${day - 1}']`);
if (dayOption) {
daySelector.removeChild(dayOption);
}
}
}
How does it work
It saves options for day 29,30 and 31 to a tailDayOptions array
When user changes the year or month, daysInMonth are calculated
If a given day (e.g. 29th) is not present in a given year-month and it is available in the select options, it gets removed from there
If a given day is available in a given year-month it gets re-added to the select from the tailDayOptions array
Compatibility
Compatible with Firefox, Chrome and Safari. Should be compatible with all other browsers.

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>

jQuery .hide() and CSS display:none; are not working on <option> element in Safair 9.0.3 [duplicate]

This should work:
$('option').hide(); // hide options
It works in Firefox, but not Chrome (and probably not in IE, not tested).
A more interesting example:
<select>
<option class="hide">Hide me</option>
<option>visible option</option>
</select>
<script type="text/javascript">
// try to hide the first option
$('option.hide').hide();
// to select the first visible option
$('option:visible').first().attr('selected', 'selected');
</script>
Or see the example at http://jsfiddle.net/TGxUf/
Is the only option to detach the option elements from the DOM? I need to show them again later, so this would not be very effective.
Unfortunately, you can't hide option elements in all browsers.
In the past when I have needed to do this, I have set their disabled attribute, like so...
$('option').prop('disabled', true);
I've then used the hiding where it is supported in browsers using this piece of CSS...
select option[disabled] {
display: none;
}
As has been said, you can't display:none individual <option>s, because they're not the right kind of DOM elements.
You can set .prop('disabled', true), but this only grays out the elements and makes them unselectable -- they still take up space.
One solution I use is to .detach() the <select> into a global variable on page load, then add back only the <option>s you want on demand. Something like this (http://jsfiddle.net/mblase75/Afe2E/):
var $sel = $('#sel option').detach(); // global variable
$('a').on('click', function (e) {
e.preventDefault();
var c = 'name-of-class-to-show';
$('#sel').empty().append( $sel.filter('.'+c) );
});
At first I thought you'd have to .clone() the <option>s before appending them, but apparently not. The original global $sel is unaltered after the click code is run.
If you have an aversion to global variables, you could store the jQuery object containing the options as a .data() variable on the <select> element itself (http://jsfiddle.net/mblase75/nh5eW/):
$('#sel').data('options', $('#sel option').detach()); // data variable
$('a').on('click', function (e) {
e.preventDefault();
var $sel = $('#sel').data('options'), // jQuery object
c = 'name-of-class-to-show';
$('#sel').empty().append( $sel.filter('.'+c) );
});
Had a crack at it myself and this is what I came up with:
(function($){
$.fn.extend({detachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
s.find(o).each(function() {
d.push($(this).detach());
});
s.data('selectOptions', d);
});
}, attachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
for (var i in d) {
if (d[i].is(o)) {
s.append(d[i]);
console.log(d[i]);
// TODO: remove option from data array
}
}
});
}});
})(jQuery);
// example
$('select').detachOptions('.removeme');
$('.b').attachOptions('[value=1]');');
You can see the example at http://www.jsfiddle.net/g5YKh/
The option elements are fully removed from the selects and can be re-added again by jQuery selector.
Probably needs a bit of work and testing before it works well enough for all cases, but it's good enough for what I need.
I know this is a little late but better late than never! Here's a really simple way to achieve this. Simply have a show and hide function. The hide function will just append every option element to a predetermined (hidden) span tag (which should work for all browsers) and then the show function will just move that option element back into your select tag. ;)
function showOption(value){
$('#optionHolder option[value="'+value+'"]').appendTo('#selectID');
}
function hideOption(value){
$('select option[value="'+value+'"]').appendTo('#optionHolder');
}
Hiding an <option> element is not in the spec. But you can disable them, which should work cross-browser.
$('option.hide').prop('disabled', true);
http://www.w3.org/TR/html401/interact/forms.html#h-17.6
You can try wrapping the option elements inside a span so that they wont be visible but still be loaded in the DOM. Like below
jQ('#ddlDropdown option').wrap('<span>');
And unwrap the option which contains the 'selected' attribute as follows to display already selected option.
var selectedOption = jQ('#ddlDropdown').find("[selected]");
jQ(selectedOption).unwrap();
This works across all the browsers.
Here's an option that:
Works in all browsers
Preserves current selection when filtering
Preserves order of items when removing / restoring
No dirty hacks / invalid HTML
$('select').each(function(){
var $select = $(this);
$select.data('options', $select.find('option'));
});
function filter($select, search) {
var $prev = null;
var $options = $select.data('options');
search = search.trim().toLowerCase();
$options.each(function(){
var $option = $(this);
var optionText = $option.text();
if(search == "" || optionText.indexOf(search) >= 0) {
if ($option.parent().length) {
$prev = $option;
return;
}
if (!$prev) $select.prepend($option);
else $prev.after($option);
$prev = $option;
} else {
$option.remove();
}
});
}
JSFiddle: https://jsfiddle.net/derrh5tr/
On pure JS:
let select = document.getElementById("select_id")
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');
to unhide just
to_hide.removeAttr('hidden');
or
to_hide.hidden = true; // to hide
to_hide.hidden = false; // to unhide
Three years late, but my Googling brought me here so hopefully my answer will be useful for someone else.
I just created a second option (which I hid with CSS) and used Javascript to move the s backwards and forwards between them.
<select multiple id="sel1">
<option class="set1">Blah</option>
</select>
<select multiple id="sel2" style="display:none">
<option class="set2">Bleh</option>
</select>
Something like that, and then something like this will move an item onto the list (i.e., make it visible). Obviously adapt the code as needed for your purpose.
$('#sel2 .set2').appendTo($('#sel1'))
It's possible if you keep in object and filter it in short way.
<select id="driver_id">
<option val="1" class="team_opion option_21">demo</option>
<option val="2" class="team_opion option_21">xyz</option>
<option val="3" class="team_opion option_31">ab</option>
</select>
-
team_id= 31;
var element = $("#driver_id");
originalElement = element.clone(); // keep original element, make it global
element.find('option').remove();
originalElement.find(".option_"+team_id).each(function() { // change find with your needs
element.append($(this)["0"].outerHTML); // append found options
});
https://jsfiddle.net/2djv7zgv/4/
This is an enhanced version of #NeverEndingLearner's answer:
full browsers support for not using unsupported CSS
reserve positions
no multiple wrappings
$("#hide").click(function(){
$("select>option.hide").wrap('<span>'); //no multiple wrappings
});
$("#show").click(function(){
$("select span option").unwrap(); //unwrap only wrapped
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<select>
<option class="hide">Hide me</option>
<option>visible option</option>
</select>
<button id="hide">hide</button>
<button id="show">show</button>
Since you mentioned that you want to re-add the options later, I would suggest that you load an array or object with the contents of the select box on page load - that way you always have a "master list" of the original select if you need to restore it.
I made a simple example that removes the first element in the select and then a restore button puts the select box back to it's original state:
http://jsfiddle.net/CZcvM/
Try this:
$(".hide").css("display","none");
But I think it doesn't make sense to hide it. if you wanna remove it, just:
$(".hide").remove();
just modify dave1010's code for my need
(function($){
$.fn.extend({hideOptions: function() {
var s = this;
return s.each(function(i,e) {
var d = $.data(e, 'disabledOptions') || [];
$(e).find("option[disabled=\"disabled\"]").each(function() {
d.push($(this).detach());
});
$.data(e, 'disabledOptions', d);
});
}, showOptions: function() {
var s = this;
return s.each(function(i,e) {
var d = $.data(e, 'disabledOptions') || [];
for (var i in d) {
$(e).append(d[i]);
}
});
}});
})(jQuery);
http://jsfiddle.net/AbzL3/1/
I thought I was bright ;-)
In CSS:
option:disabled {display:none;}
In Firefox and Chrome, a select with only the enabled options were created. Nice.
In IE, the enabled options were shown, the disabled where just blank lines, in their original location. Bad.
In Edge, the enabled options shown at top, followed by blank lines for disabled options. Acceptable.
document.getElementById('hide').style.visibility='hidden';
ive used id here for option

How can I hide select options with JavaScript? (Cross browser)

This should work:
$('option').hide(); // hide options
It works in Firefox, but not Chrome (and probably not in IE, not tested).
A more interesting example:
<select>
<option class="hide">Hide me</option>
<option>visible option</option>
</select>
<script type="text/javascript">
// try to hide the first option
$('option.hide').hide();
// to select the first visible option
$('option:visible').first().attr('selected', 'selected');
</script>
Or see the example at http://jsfiddle.net/TGxUf/
Is the only option to detach the option elements from the DOM? I need to show them again later, so this would not be very effective.
Unfortunately, you can't hide option elements in all browsers.
In the past when I have needed to do this, I have set their disabled attribute, like so...
$('option').prop('disabled', true);
I've then used the hiding where it is supported in browsers using this piece of CSS...
select option[disabled] {
display: none;
}
As has been said, you can't display:none individual <option>s, because they're not the right kind of DOM elements.
You can set .prop('disabled', true), but this only grays out the elements and makes them unselectable -- they still take up space.
One solution I use is to .detach() the <select> into a global variable on page load, then add back only the <option>s you want on demand. Something like this (http://jsfiddle.net/mblase75/Afe2E/):
var $sel = $('#sel option').detach(); // global variable
$('a').on('click', function (e) {
e.preventDefault();
var c = 'name-of-class-to-show';
$('#sel').empty().append( $sel.filter('.'+c) );
});
At first I thought you'd have to .clone() the <option>s before appending them, but apparently not. The original global $sel is unaltered after the click code is run.
If you have an aversion to global variables, you could store the jQuery object containing the options as a .data() variable on the <select> element itself (http://jsfiddle.net/mblase75/nh5eW/):
$('#sel').data('options', $('#sel option').detach()); // data variable
$('a').on('click', function (e) {
e.preventDefault();
var $sel = $('#sel').data('options'), // jQuery object
c = 'name-of-class-to-show';
$('#sel').empty().append( $sel.filter('.'+c) );
});
Had a crack at it myself and this is what I came up with:
(function($){
$.fn.extend({detachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
s.find(o).each(function() {
d.push($(this).detach());
});
s.data('selectOptions', d);
});
}, attachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
for (var i in d) {
if (d[i].is(o)) {
s.append(d[i]);
console.log(d[i]);
// TODO: remove option from data array
}
}
});
}});
})(jQuery);
// example
$('select').detachOptions('.removeme');
$('.b').attachOptions('[value=1]');');
You can see the example at http://www.jsfiddle.net/g5YKh/
The option elements are fully removed from the selects and can be re-added again by jQuery selector.
Probably needs a bit of work and testing before it works well enough for all cases, but it's good enough for what I need.
I know this is a little late but better late than never! Here's a really simple way to achieve this. Simply have a show and hide function. The hide function will just append every option element to a predetermined (hidden) span tag (which should work for all browsers) and then the show function will just move that option element back into your select tag. ;)
function showOption(value){
$('#optionHolder option[value="'+value+'"]').appendTo('#selectID');
}
function hideOption(value){
$('select option[value="'+value+'"]').appendTo('#optionHolder');
}
Hiding an <option> element is not in the spec. But you can disable them, which should work cross-browser.
$('option.hide').prop('disabled', true);
http://www.w3.org/TR/html401/interact/forms.html#h-17.6
You can try wrapping the option elements inside a span so that they wont be visible but still be loaded in the DOM. Like below
jQ('#ddlDropdown option').wrap('<span>');
And unwrap the option which contains the 'selected' attribute as follows to display already selected option.
var selectedOption = jQ('#ddlDropdown').find("[selected]");
jQ(selectedOption).unwrap();
This works across all the browsers.
Here's an option that:
Works in all browsers
Preserves current selection when filtering
Preserves order of items when removing / restoring
No dirty hacks / invalid HTML
$('select').each(function(){
var $select = $(this);
$select.data('options', $select.find('option'));
});
function filter($select, search) {
var $prev = null;
var $options = $select.data('options');
search = search.trim().toLowerCase();
$options.each(function(){
var $option = $(this);
var optionText = $option.text();
if(search == "" || optionText.indexOf(search) >= 0) {
if ($option.parent().length) {
$prev = $option;
return;
}
if (!$prev) $select.prepend($option);
else $prev.after($option);
$prev = $option;
} else {
$option.remove();
}
});
}
JSFiddle: https://jsfiddle.net/derrh5tr/
On pure JS:
let select = document.getElementById("select_id")
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');
to unhide just
to_hide.removeAttr('hidden');
or
to_hide.hidden = true; // to hide
to_hide.hidden = false; // to unhide
Three years late, but my Googling brought me here so hopefully my answer will be useful for someone else.
I just created a second option (which I hid with CSS) and used Javascript to move the s backwards and forwards between them.
<select multiple id="sel1">
<option class="set1">Blah</option>
</select>
<select multiple id="sel2" style="display:none">
<option class="set2">Bleh</option>
</select>
Something like that, and then something like this will move an item onto the list (i.e., make it visible). Obviously adapt the code as needed for your purpose.
$('#sel2 .set2').appendTo($('#sel1'))
It's possible if you keep in object and filter it in short way.
<select id="driver_id">
<option val="1" class="team_opion option_21">demo</option>
<option val="2" class="team_opion option_21">xyz</option>
<option val="3" class="team_opion option_31">ab</option>
</select>
-
team_id= 31;
var element = $("#driver_id");
originalElement = element.clone(); // keep original element, make it global
element.find('option').remove();
originalElement.find(".option_"+team_id).each(function() { // change find with your needs
element.append($(this)["0"].outerHTML); // append found options
});
https://jsfiddle.net/2djv7zgv/4/
This is an enhanced version of #NeverEndingLearner's answer:
full browsers support for not using unsupported CSS
reserve positions
no multiple wrappings
$("#hide").click(function(){
$("select>option.hide").wrap('<span>'); //no multiple wrappings
});
$("#show").click(function(){
$("select span option").unwrap(); //unwrap only wrapped
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<select>
<option class="hide">Hide me</option>
<option>visible option</option>
</select>
<button id="hide">hide</button>
<button id="show">show</button>
Since you mentioned that you want to re-add the options later, I would suggest that you load an array or object with the contents of the select box on page load - that way you always have a "master list" of the original select if you need to restore it.
I made a simple example that removes the first element in the select and then a restore button puts the select box back to it's original state:
http://jsfiddle.net/CZcvM/
Try this:
$(".hide").css("display","none");
But I think it doesn't make sense to hide it. if you wanna remove it, just:
$(".hide").remove();
just modify dave1010's code for my need
(function($){
$.fn.extend({hideOptions: function() {
var s = this;
return s.each(function(i,e) {
var d = $.data(e, 'disabledOptions') || [];
$(e).find("option[disabled=\"disabled\"]").each(function() {
d.push($(this).detach());
});
$.data(e, 'disabledOptions', d);
});
}, showOptions: function() {
var s = this;
return s.each(function(i,e) {
var d = $.data(e, 'disabledOptions') || [];
for (var i in d) {
$(e).append(d[i]);
}
});
}});
})(jQuery);
http://jsfiddle.net/AbzL3/1/
I thought I was bright ;-)
In CSS:
option:disabled {display:none;}
In Firefox and Chrome, a select with only the enabled options were created. Nice.
In IE, the enabled options were shown, the disabled where just blank lines, in their original location. Bad.
In Edge, the enabled options shown at top, followed by blank lines for disabled options. Acceptable.
document.getElementById('hide').style.visibility='hidden';
ive used id here for option

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);
}
}

Hiding <option>s in IE

I wrote this nifty function to filter select boxes when their value is changed...
$.fn.cascade = function() {
var opts = this.children('option');
var rel = this.attr('rel');
$('[name='+rel+']').change(function() {
var val = $(this).val();
var disp = opts.filter('[rel='+val+']');
opts.filter(':visible').hide();
disp.show();
if(!disp.filter(':selected').length) {
disp.filter(':first').attr('selected','selected');
}
}).trigger('change');
return this;
}
It looks at the rel property, and if the element indicated by rel changes, then it filters the list to only show the options that have that value... for example, it works on HTML that looks like this:
<select id="id-pickup_address-country" name="pickup_address-country">
<option selected="selected" value="CA">Canada
</option>
<option value="US">United States
</option>
</select>
<select id="id-pickup_address-province" rel="pickup_address-country" name="pickup_address-province">
<option rel="CA" value="AB">Alberta
</option>
<option selected="selected" rel="CA" value="BC">British Columbia
</option>
<option rel="CA" value="MB">Manitoba
</option>...
</select>
However, I just discovered it doesn't work properly in IE (of course!) which doesn't seem to allow you to hide options. How can I work around this?
Here's what I've got now:
(function($) {
$.fn.cascade = function() {
var filteredSelect = $(this);
var filteredOpts = this.children('option');
var triggerSelect = $('[name='+this.attr('rel')+']');
triggerSelect.change(function() {
var triggerValue = $(this).val();
filteredOpts.detach()
.filter('[rel='+triggerValue+']').appendTo(filteredSelect)
.filter(':first').attr('selected','selected');
}).trigger('change');
return this;
}
})(jQuery);
Which does work in IE, but still has two problems. The .filter(':first').attr('selected','selected'); bit doesn't seem to do anything in IE (it should select the first visible element). Since I've been using appendTo it currently defaults to the last. And the other problem is that since I detach all the elements immediately, you can't have default values in your HTML.
Options cannot be marked hidden. You must use the SelectElement.add(option) and SelectElement.remove(index)...
Here is a link to remove and add select Options in the same order.
How can I restore the order of an (incomplete) select list to its original order?
Here is a link where I made a post for just doing the most simple thing
How to hide optgroup/option elements?
Note in my post the try catch. This is necessary when adding elements expecially when making the site usable in firefox and IE.

Categories