Related
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
I've got a Problem. I have a Select Option in HTML
<div id="eilig">
<select id="eiligselect" data-role="slider">
<option value="2" selected="selected">n. Eilig</option>
<option value="1">Eilig</option>
</select>
</div>
On page default "n. Eilig" is selected. After I have made a ajax post request (with "Eilig" selected) the select option should go back to default ("n. Eilig")
I have tried it with $('#eiligselect').val(2); but this only change the value back but the select option shows "Eilig" (but internal value is "n. Eilig".
This select is with a data-role "slider" which emulates a on / off switch like in ios.
So I think I have to click that slider with javascript to change it back instead of just change the value.
Do you have a clue? Thanks.
Try this : put selected attribute for option with value="2"
$('#eiligselect option[value="2"]').attr('selected',true);
Bind the event on change for slider on select value change,
$('#eiligselect').on('change', function() {
var activeLabel = $('span.ui-slider-label');
var mySlider = $(this);
var new2 = 'n. Eilig';
var new1 = 'Eilig';
if(mySlider.val() == 1) {
activeLabel.text(new2);
} else {
activeLabel.text(new1);
}
mySlider.slider( 'refresh' ); // .trigger( 'create' )
});
This Code may help you solving your problem,
var eiligselect = $("#eiligselect")[0];
eiligselect.seletedIndex = 0;
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.
I have a PHP page that creates multiple selects depending on how many the page before it gives it and creates the same number of options that there are selected (it's to choose the priority).
<select name="select1" id="idSelect" onchange="javascript:SelectOnChange();">
<option value="Select one">Select one</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
What I want to do is, whenever the user chooses an option that was already selected in another selection, to show an alert in order to let them know that their choice has already been taken and deny the change.
I want to compare the currently selected option to every previously selected option every time the user selects something from every select.
Basically your looking for a change event to loop through each select and notify duplicates.
$("select").change(function() {
var currentSelection = this.value;
$("select").each(function() {
if (this.value == currentSelection) {
alert("you've already chosen this!");
}
});
});
Something like this should work
Listen for change events
Get the element's seletedIndex
Grab all of the selects with getElementsByTagName()
Loop through and get the selected index
Compare to see if used
This could maybe work :
var $selects = $('select');
// WHen a select is changed.
$selects.onchange(function() {
// Storing it's selected value, assuming there is only one per select.
var value = $(this).selected().first().attr('value');
var $changedSelect = $(this);
// For each select...
$selects.each(function() {
var $otherSelect = $(this);
// ...that is not the one that just changed.
if( ! $otherSelect.is($changedSelect)) {
// If that other select's selected value is the same as the changed one's
if($otherSelect.selected().first().attr('value') === value) {
alert('...');
}
}
});
}
I didn't try it though, you might have to change a few details in it if it doesn't work.
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