Hide Dropdown List Value, when another dropdown value selected Javascript - 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>

Related

Order of Select2 selection based on array of items

I'm trying to set the order of selected items in Select2 based on an array.
A simple solution has already been proposed to append items in the order with which they are clicked in the dropdown menu (see 2rba's answer on 2017-10-26 in this discussion):
$("#selectCriteria").on("select2:select", function (evt) {
var element = evt.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
});
What I'm trying to do is mimick this behavior, but when passing an array of the selected items instead of manually clicking them in the list. I tried the following command:
displayed_items = ["b", "c", "a"];
$('#selectCriteria').val(displayed_items).trigger('change');
But the order isn't preserved. I tried looping the command with one element at a time, but each new call overwrites the previous element:
$('#selectCriteria').val("b").trigger('change');
$('#selectCriteria').val("c").trigger('change');
$('#selectCriteria').val("a").trigger('change');
I see two possible solutions to this, but lack the background to make them work:
How should the iteration above be adapted to not overwrite the previously added
value?
How could I incorporate the approach shown in this
fiddle (from vol7ron's posts on github) which does pretty
much what I'm asking (i.e. toggling on/off the
.data('preserved-order',selected))? As it is using JSX I'm
not sure how I could reuse that script in my plain JS/jQuery script.
here you go
EDIT:
this is not the prettiest solution, but it gets the job done.
you would have to call initSelect function that takes an array of values as a parameter. i left some comments in the code.
displayed_items = $('#selected_items').val().split(',');
function selectItem(target, id) { // refactored this a bit, don't pay attention to this being a function
var option = $(target).children('[value='+id+']');
option.detach();
$(target).append(option).change();
}
function customPreSelect() {
let items = $('#selected_items').val().split(',');
$("select").val('').change();
initSelect(items);
}
function initSelect(items) { // pre-select items
items.forEach(item => { // iterate through array of items that need to be pre-selected
let value = $('select option[value='+item+']').text(); // get items inner text
$('select option[value='+item+']').remove(); // remove current item from DOM
$('select').append(new Option(value, item, true, true)); // append it, making it selected by default
});
}
$('select').select2();
$('select').on('select2:select', function(e){
selectItem(e.target, e.params.data.id);
});
initSelect(displayed_items); // call init
select {
width: 50%;
}
.container {
display: flex;
flex-direction: column;
}
.control-group {
padding-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<div class="container">
<p>Provide comma separated items to be pre selected and click the button</p>
<div class="control-group">
<input id="selected_items" value="b,c,a"/>
<button onclick="customPreSelect()">Init</button>
</div>
<select multiple="multiple">
<option value="a">A</option>
<option value="b" >B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
</div>
This preserves attributes of the select2 options (e.g. titles used for tooltips):
function initSelect(items) {
items.forEach(item => {
var option = $('#selectCriteria').children('[value="' + item + '"]');
option[0].selected = true;
option.detach();
$('#selectCriteria').append(option).change();
})
}

Create new drop downs on change event using jQuery

I have drop down menu with some random values. When I select the value onchange event triggers and I want to add new drop down under it, but the new one should have all values except selected one in first drop down. Now when I change value of second one, I need third one that has only non selected values from previous two drop downs and so on until there is no more option to select.
What I have for now is mechanism for adding new drop downs, but it is not working correctly. If I for example select first value it will do the job, new drop down is shown and it has all options except selected one. But then if I go back and try to change option for first drop down third drop down is created. This should not be a case, if drop down already created another drop down it should not do it again. Is it even possible to avoid triggering of new onchange event for drop down that already triggered one? Or maybe some other kind of event is more suitable for this case?
This is my function that does described job:
createNewDropDonws : function() {
var selectWrapper = $('#select-boxes');
$(document).on('change', '.dynamic-select', function() {
var element = $(this);
var optionsLength = (element.find('option').length) - 1;
if(optionsLength === 1) {
return true;
}
var newSelect = $(this).clone();
newSelect.find("option[value='" + element.val() + "']").remove();
newSelect.appendTo(selectWrapper)
});
}
This is my HTML for drop down:
<div id="select-boxes">
<select class="dynamic-select" id="ddlTest">
<option value=""></option>
<option value="Belbin">Belbin</option>
<option value="Raven">Raven</option>
<option value="PPA">PPA</option>
<option value="PPA+">PPA+</option>
<option value="Basic Knowledge">Basic Knowledge</option>
<option value="PCT">PCT</option>
</select>
</div>
And this is simple CSS class:
.dynamic-select{
display: block;
margin: 10px;
}
Does anybody has any idea how this can be implemented correctly by using jQuery?
We can do it in following way:
We are just adding some class like executed once it add another dropdown. And in event handler we are checking if current dropdwon has that class or not. If it is already there then it means we are already done with that dropdown as follows:
$(document).ready(function() {
var selectWrapper = $('#select-boxes');
$(document).on('change', '.dynamic-select', function() {
var element = $(this);
if(element.hasClass("executed"))
return;
var optionsLength = (element.find('option').length) - 1;
if (optionsLength === 1) {
return true;
}
var newSelect = $(this).clone();
newSelect.find("option[value='" + element.val() + "']").remove();
newSelect.appendTo(selectWrapper)
$(this).addClass("executed");
});
});
.dynamic-select {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="select-boxes">
<select class="dynamic-select" id="ddlTest">
<option value=""></option>
<option value="Belbin">Belbin</option>
<option value="Raven">Raven</option>
<option value="PPA">PPA</option>
<option value="PPA+">PPA+</option>
<option value="Basic Knowledge">Basic Knowledge</option>
<option value="PCT">PCT</option>
</select>
</div>

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.

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

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.

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