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
Related
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/
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 didn't expect it but the following test fails on the cloned value check:
test("clone should retain values of select", function() {
var select = $("<select>").append($("<option>")
.val("1"))
.append($("<option>")
.val("2"));
$(select).val("2");
equals($(select).find("option:selected").val(), "2", "expect 2");
var clone = $(select).clone();
equals($(clone).find("option:selected").val(), "2", "expect 2");
});
Is this right?
After further research I found this ticket in the JQuery bug tracker system which explains the bug and provides a work around. Apparently, it is too expensive to clone the select values so they won't fix it.
https://bugs.jquery.com/ticket/1294
My use of the clone method was in a generic method where anything might be cloned so I'm not sure when or if there will be a select to set the value on. So I added the following:
var selects = $(cloneSourceId).find("select");
$(selects).each(function(i) {
var select = this;
$(clone).find("select").eq(i).val($(select).val());
});
Here's a fixed version of the clone method for jQuery:
https://github.com/spencertipping/jquery.fix.clone
// Textarea and select clone() bug workaround | Spencer Tipping
// Licensed under the terms of the MIT source code license
// Motivation.
// jQuery's clone() method works in most cases, but it fails to copy the value of textareas and select elements. This patch replaces jQuery's clone() method with a wrapper that fills in the
// values after the fact.
// An interesting error case submitted by Piotr PrzybyĆ: If two <select> options had the same value, the clone() method would select the wrong one in the cloned box. The fix, suggested by Piotr
// and implemented here, is to use the selectedIndex property on the <select> box itself rather than relying on jQuery's value-based val().
(function (original) {
jQuery.fn.clone = function () {
var result = original.apply(this, arguments),
my_textareas = this.find('textarea').add(this.filter('textarea')),
result_textareas = result.find('textarea').add(result.filter('textarea')),
my_selects = this.find('select').add(this.filter('select')),
result_selects = result.find('select').add(result.filter('select'));
for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
return result;
};
}) (jQuery.fn.clone);
Made a plugin out of chief7's answer:
(function($,undefined) {
$.fn.cloneSelects = function(withDataAndEvents, deepWithDataAndEvents) {
var $clone = this.clone(withDataAndEvents, deepWithDataAndEvents);
var $origSelects = $('select', this);
var $clonedSelects = $('select', $clone);
$origSelects.each(function(i) {
$clonedSelects.eq(i).val($(this).val());
});
return $clone;
}
})(jQuery);
Only tested it briefly, but it seems to work.
My approach is a little different.
Instead of modifying selects during cloning, I'm just watching every select on page for change event, and then, if value is changed I add needed selected attribute to selected <option> so it becomes <option selected="selected">. As selection is now marked in <option>'s markup, it will be passed when you'll .clone() it.
The only code you need:
//when ANY select on page changes its value
$(document).on("change", "select", function(){
var val = $(this).val(); //get new value
//find selected option
$("option", this).removeAttr("selected").filter(function(){
return $(this).attr("value") == val;
}).first().attr("selected", "selected"); //add selected attribute to selected option
});
And now, you can copy select any way you want and it'll have it's value copied too.
$("#my-select").clone(); //will have selected value copied
I think this solution is less custom so you don't need to worry if your code will break if you'll modify something later.
If you don't want it to be applied to every select on page, you can change selector on the first line like:
$(document).on("change", "select.select-to-watch", function(){
Simplification of chief7's answer:
var cloned_form = original_form.clone()
original_form.find('select').each(function(i) {
cloned_form.find('select').eq(i).val($(this).val())
})
Again, here's the jQuery ticket: http://bugs.jquery.com/ticket/1294
Yes. This is because the 'selected' property of a 'select' DOM node differs from the 'selected' attribute of the options. jQuery does not modify the options' attributes in any way.
Try this instead:
$('option', select).get(1).setAttribute('selected', 'selected');
// starting from 0 ^
If you're really interested in how the val function works, you may want to examine
alert($.fn.val)
Cloning a <select> does not copy the value= property on <option>s. So Mark's plugin does not work in all cases.
To fix, do this before cloning the <select> values:
var $origOpts = $('option', this);
var $clonedOpts = $('option', $clone);
$origOpts.each(function(i) {
$clonedOpts.eq(i).val($(this).val());
});
A different way to clone which <select> option is selected, in jQuery 1.6.1+...
// instead of:
$clonedSelects.eq(i).val($(this).val());
// use this:
$clonedSelects.eq(i).prop('selectedIndex', $(this).prop('selectedIndex'));
The latter allows you to set the <option> values after setting the selectedIndex.
$(document).on("change", "select", function(){
original = $("#original");
clone = $(original.clone());
clone.find("select").val(original.find("select").val());
});
If you just need the value of the select, to serialize the form or something like it, this works for me:
$clonedForm.find('theselect').val($origForm.find('theselect').val());
After 1 hour of trying different solutions that didn't work, I did create this simple solution
$clonedItem.find('select option').removeAttr('selected');
$clonedItem.find('select option[value="' + $originaItem.find('select').val() + '"]').attr('selected', 'true');
#pie6k show an good idea.
It solved my problem. I change it a little small:
$(document).on("change", "select", function(){
var val = $(this).val();
$(this).find("option[value=" + val + "]").attr("selected",true);
});
just reporting back. For some godly unknown reason, and even though this was the first thing I tested, and I haven't changed my code whatsoever, now the
$("#selectTipoIntervencion1").val($("#selectTipoIntervencion0").val());
approach is working. I have no idea why or if it will stop working again as soon as I change something, but I'm gonna go with this for now. Thanks everybody for the help!
http://jsfiddle.net/bGDME/
Basically, I want to show only whatever is selected in the scope and hide the rest.
The way I did it seems so.. I don't know. Tedious.
I was hoping to get some ideas of making it better. A point in the right direction would be very much appreciated, too.
Thanks.
You can minimize the code by using toggle() instead of your if/else statements
Working Example: http://jsfiddle.net/hunter/bGDME/1/
$('#scope').change( function(){
var type = $('option:selected', this).val();
$('#grade').toggle(type == 2 || type == 3);
$('#class').toggle(type == 3);
});
.toggle(showOrHide)
showOrHide: A Boolean indicating whether to show or hide the elements.
This seems fine to me, unless you have lots of or dynamic controls. However u can use JQuery addClass / removeClass, switch statement, multiple Selector $('#grade, #class').show(); to minimize the code
you can also use a switch state: http://jsfiddle.net/bGDME/3/
Here's an approach using HTML5 data attributes to declaratively set "scope levels" on the select boxes: http://jsfiddle.net/bGDME/6/
And the updated JavaScript:
var $scopedSelects = $('#grade, #class').hide();
$('#scope').change( function(){
var scopeLevel = $(this).val();
$scopedSelects.each(function() {
var $this = $(this);
$this[$this.data('scope-level') <= scopeLevel ? 'show' : 'hide']();
});
});
The primary advantage this one might have is that the code stays the same regardless of how many "scoped selects" you have (assuming you update the initial selector, of course).
what about this??
$(document).ready( function() {
$('#grade, #class').hide();
$('#scope').change( function(){
var type = $('option:selected', this).text();
alert(type);
$('select').next().not('#'+type).hide();
$('#'+type).show();
});
});
DEMO
Its very simple,
$(document).ready( function() {
$("select[id!='scope'][id!='school']").hide();
$('#scope').change( function(){
$("select[id!='scope']").hide();
var ken=$(this).val();
$("#"+ken).show();
});
});
If you want to make it a bit more dynamic by not touching the javascript when you want to add more select elements, then you can do small changes to your javascript code and HTML and you will only need to edit the HTML
Javascript:
$(document).ready(function() {
$('#scope').change(function() {
var type = $(this).val().split(',');
$('.values select').hide();
for (x in type) {
$('.values').find('#'+type[x]).show();
}
});
});
HTML:
<select id='scope'>
<option value=''>Select</option>
<option value='school'>school</option>
<option value='school,grade'>grade</option>
<option value='school,grade,class'>class</option></select>
This will do what you're looking for: http://jsfiddle.net/bGDME/30/
You simply use the val() of the scope within the eq() method to determine which sibling select should remain shown. If 'school' is chosen from the first dropdown, then neither get shown:
$(document).ready( function() {
var additionalSelects = $('#grade, #class');
$('#scope').change(function(){
var selectedVal = $(this).val();
additionalSelects.hide();
if(selectedVal > 1){
additionalSelects.eq(selectedVal - 2).show();
}
});
});
I have a select box in which i can select multiple options. In the select box are multiple optgroups.
Is there an easy way to select a whole optgroup at once in javascript?
I suggest using jQuery (or another framework) to quickly handle DOM selections. Give each optgroup a class to make it easier to grab it.
$("optgroup.className").children().attr('selected','selected');
If you want to select the entire group based on the user selecting the group, do the following:
$("optgroup.className").select(function(e) {
$(this).children().attr('selected','selected');
});
**Both examples are untested pseudo-code, but they should work with minimal changes, if necessary.
If you cannot use a framework, you'll have to traverse the DOM yourself to find the optgroup and children. You could attach a listener to the select element to grab the element being selected then traverse to the children that way, too.
I'm normally against using jQuery for simple jobs like this but I can see its value here. Still, if you prefer a non-jQuery solution that will have the benefits of using no library, introducing no spurious ids or classes and running faster, here is one:
<script type="text/javascript">
function selectOptGroupOptions(optGroup, selected) {
var options = optGroup.getElementsByTagName("option");
for (var i = 0, len = options.length; i < len; i++) {
options[i].selected = selected;
}
}
function selectOptGroup(selectId, label, selected) {
var selectElement = document.getElementById(selectId);
var optGroups = selectElement.getElementsByTagName("optgroup");
var i, len, optGroup;
for (i = 0, len = optGroups.length; i < len; i++) {
optGroup = optGroups[i];
if (optGroup.label === label) {
selectOptGroupOptions(optGroup, selected);
return;
}
}
}
</select>
<select id="veg" multiple>
<optgroup label="roots">
<option>Swede</option>
<option>Carrot</option>
<option>Turnip</option>
</optgroup>
<optgroup label="leaves">
<option>Spinach</option>
<option>Kale</option>
</optgroup>
</select>
<input type="button" onclick="selectOptGroup('veg', 'roots', true)" value="Select roots">
If your <optgroup> has an id you could do away with the selectOptGroup function and just pass the optgroup straight into selectOptGroupOptions.
jquery:
$('#myoptgroup option').attr('selected', true);
I was trying to do something similar just now.
I wanted to select an <optgroup>'s <option>s upon clicking the group's label. The first attempt went like this:
$('select > optgroup').click(function () {
$(this).children().attr('selected', true);
});
This solution half worked...
Upon clicking the <optgroup>'s label all of its children became selected.
BUT when simply clicking an <option> it was still selecting all the other <option>s in the group! The problem was event bubbling, because the <option> is inside the <optgroup> technically you're clicking it too.
Therefore the final piece of the puzzle was to suppress the event bubbling upwards in the event that an <option> was actually clicked instead. The final solution then became:
$('select > optgroup').click(function () {
$(this).children().attr('selected', true);
});
$('select > optgroup > option').click(function (e) {
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
});
Job done!
EDIT
Infuriatingly this doesn't work work in IE8 (and doubtful < IE8 - maybe IE9?)...
It decides to totally ignore click events on both and elements. The only alternative that I can think of is to position elements above the optgroup labels to capture the click, but its probably not worth the effort...