How to hide/show an option on click?
The select is sometimes too big so I want to filter it. I will have 3 checkboxes to turn off/on some options based on values. Like in the sample on jsfiddle
- if the value of an option contains
d
hide it - in my example we need to hide 2 options - if the checkbox is unchecked show the value
Could be done in jQuery.开发者_StackOverflow Any idea how?
It is good enough for me if it works in firefox ( chrome is good too but not necessary, the same for safari )
NOTE:
There are going to be 3 checkboxes to filter values that contain w
, d
and ,h
. So the hiding/showing must work for all of them.
Final code on jsfiddle based on @ShankarSangoli answer.
Hiding an option
in a select list is not supported in all the browsers. jQuery
even cannot do anything to make it cross browser supported. But we can disable the option using disabled
property.
Here is the working demo with option disabled on checkbox click.
http://jsfiddle.net/ggWJu/8/
Here is the working demo to add/remove option from the select box on checkbox click. It adds the option at the same location where it was removed from.
http://jsfiddle.net/ggWJu/9/
Here is the fiddle which will add/remove all the options if the option value contains the checkbox value.
http://jsfiddle.net/ggWJu/10/
This works with your example (jsFiddle):
$('input:checkbox').click(function() {
if (this.checked) {
$('select option[value$=d]').hide();
} else {
$('select option[value$=d]').show();
}
});
The selector option[value$=d]
finds option
s with values that end with "d".
Additionally, I would give your select
and input
elements some unique IDs so you can pinpoint them as the elements you want to control with jQuery -- this may affect other elements on your page as it is.
Is this example what you're looking for? See change event and contains selector documentation.
What you need, is an array in your js part. then from that array, you can build a select element on the fly by itterate the array, and you can manipulate it too on the fly.
精彩评论