How to "dropdown" a select when click on somewhere else? - javascript

This is the thing I have:
A normal select with a few options...
And the thing is, I do need to click in some other div and when I click on that one, I want the select list to show up as they were clicked normally and then allow the user to choose from the select options
I have some code already
<div onclick="set_select()"></div>
<select class='form-control' id='opts'>
<option selected disabled></option>
<option>Contacto</option>
<option>Entrevista</option>
<option>Prensa</option>
<option>Conferencias</option>
</select>
<script type="text/javascript">
function set_select(){
var select = document.getElementById('opts');
return select.active = true;
}
</script>

Not possible with plain html/javascript.

You need some plugin to replace your standard select field with divs and then use your function to trigger that divs. One is selectmenu: https://jqueryui.com/selectmenu/#product-selection
There is a lot more of them available: https://www.google.pl/search?q=js+select+replacement&gws_rd=cr&ei=wN5ZV8SjMIGLsgGP_IboDQ

This is "sort" of possible but not trivial and you will need to possibly do some management of the effect as I do here in the "change" event for the select. Not perfect but perhaps this can give you a start.
Note you MIGHT just want to use the "focus" on the select or, set the visible size as I do here, set the select size on the change to 0 with event.target.size = 0; and so forth.
Revised the markup a bit to allow the click handler:
<div id="clicker">clicker</div>
<select class='form-control' id='opts'>
<option selected disabled></option>
<option>Contacto</option>
<option>Entrevista</option>
<option>Prensa</option>
<option>Conferencias</option>
</select>
Here is the script, as I said, not perfect but you can decide how you handle the change/click events.
window.onload = function() {
var id = "clicker";
var div = document.getElementById(id);
var select = document.getElementById("opts");
div.onclick = function(event) {
console.log('clicker div');
select.size = select.options.length;
select.focus();
};
select.onclick = function(event) {
console.log('opt clicked');
};
select.onchange = function(event) {
console.log('opt change');
var index = event.target.selectedIndex;
console.log(index);
event.target.size = index + 2;
};
}
Here is a fiddle you can use to get you started: https://jsfiddle.net/MarkSchultheiss/mL0b7ubr/
Note that if you wish to use the "default" size for the select you can detect that like so:
if (event.target.type == "select-one") {
event.target.size = 1;
} else {
event.target.size = 4;
}
Here is a fiddle with that change and a bit cleaner on the event attachment: https://jsfiddle.net/MarkSchultheiss/mL0b7ubr/1/

Related

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

Click on a select html element

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;

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.

Creating a click function from a select element

I'm having some trouble creating a JavaScript function using an select element and id link. The function should depend on the selected option/value of the select dropdon.
What I want to do, is call an event function when the select dropdown is clicked, then apply a class to the appropriate id.
The html is this:
<select class="select-trigger" >
<option value="value1">Value1</option>
<option value="Value2">Value2</option>
<option value="Value3">Value3</option>
</select>
And the elements to get a class added:
<div id="value1"></div>
<div id="value2"></div>
<div id="value3"></div>
And my function so far (almost working):
var trigger = document.querySelectorAll('.trigger');
for (var i =0; i < trigger.length; i++) {
var btn = trigger[i];
btn.addEventListener('click', function () {
var id = this.options[this.selectedIndex].value;
document.querySelector('#' + id).classList.toggle('active');
}, false);
}
I think the trouble I'm having is that I'm calling the function using click event listener. I guess I would need to use an onchange function instead?
Also I only want a single div to have an "active" class at any given time. At the moment, the function is adding the class but not removing it when another is selected.
Here's a fiddle http://jsfiddle.net/2Rcjt/1/
Note - I don't want to put any inline onclick JS in my markup.
You can save the last selected option (div) into some property of the select. Then each time user change the option, just toggle class on the last selected option to make it inactive. Code:
var trigger = document.querySelectorAll('.trigger');
for(var i = 0; i < trigger.length; i++){
trigger[i].onchange = function(){
if(this.lastOption) this.lastOption.classList.toggle('active');
this.lastOption = document.getElementById(this.value);
this.lastOption.classList.toggle('active');
};
trigger[i].onchange();
}
Demo.

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

Categories