简体   繁体   中英

Hiding select options using JavaScript

I have the following select dropdown

<select id="strand_id" class="strand_options" name="strand[id]">
  <option value="1">Text Value</option>
  <option value="2">Text Value</option>
  <option value="3">Text Value</option>
  <option value="4">Text Value</option>
  <option value="5">Text Value</option>
  <option value="6">Text Value</option>
  <option value="7">Text Value</option>
</select>

What I want to achieve is to hide option values 4, 5, 6, and 7

So far I have an array ( strand_array ) that holds all the option values

var strand_array = [];
var select = document.getElementById('strand_id')
  for(var i=0; i < select.length; i++) {
    value = select.options[i].value;
    strand_array.push(value);
  }

  if(strand_array.indexOf('4','5','6','7') != -1 ){
    console.log('hide');
  }

What I think I need to do is then iterate through each of the strand_array values and say

"if option values are 4, 5, 6, or 7 then hide them"

So I have been looking at indexOf() but cant seem to work out how to use this correctly, I can use jQuery.inArray() fine but am struggling here (maybe its just too obvious?)

If I was to use jQuery I would do

var strand_options = $('.strand_options').find('option');
  strand_options.each(function(){
    if( jQuery.inArray($(this).val(), ['4', '5', '6', '7']) != -1 ){
      $(this).hide();
    }
 });  

So where am I not getting this?

Am I not iterating over the strand_array correctly?

Declare your array of values you want hidden:

var toHide = ['4', '5', '6', '7'];

then iterate through the options:

var sel = document.getElementById("strand_id");
for (var i = 0; i < sel.length; ++i)
  if (toHide.indexOf(sel.options[i].value) >= 0)
     sel.options[i].style.display = "none";

Use remove instead of hide

var strand_options = $('.strand_options').find('option');
  strand_options.each(function(){
    if( jQuery.inArray($(this).val(), ['4', '5', '6', '7']) != -1 ){
      $(this).remove();
    }
 });

http://jsfiddle.net/hpn4vqo9/1/

Please try this

var $strand_options = $('.strand_options').find('option');
            $strand_options.each(function () {                
                if (jQuery.inArray($(this).val(), ['4', '5', '6', '7']) != -1) {
                    $(this).hide();
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM