Naruto
Naruto

Reputation: 9634

How to hide and show select options

I'm very very new to jQuery. I Googled a lot before I'm asking, though it looks silly but for me its complicated.

I have a simple <select> list which has around 4 values like this image shown below.

enter image description here

Now at runtime, I want to hide the options and show based on index or value names in jQuery. How can I achieve this?.

My drop down box has a div region and simple select option with set of values. Please provide me a simple example.

Sample code

<Div ID = "abcd">
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
</div>

In this how to hide Volvo/Opel at run time?... like i want to show and hide these options dynamically.

Like Ex: When a button is pressed i want to hide Volvo. Similarly if another button is pressed i want to display Volvo back.

Upvotes: 3

Views: 8855

Answers (1)

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5428

if you would like to hide the whole select you should give your select or the div containing your select an id and then you can do like :

<div id="mySelect" >your select tag here </div>

$('mySelect').show(); // or $('mySelect').hide();

http://api.jquery.com/hide/

http://api.jquery.com/show/

if you would like to hide the option you can do like below :

$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();

To be more specific to your code :

<div id="abcd">
<select id="mySelect">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
</div>

title = 'volvo';
$("#mySelect option[value=" + title + "]").hide();

like in this post : Hide options in a select list using jQuery

or remove it :

JQuery: Hide options of select according to option value

Upvotes: 2

Related Questions