Home > database >  jQuery or Javascript get array of select options with values to hide elements
jQuery or Javascript get array of select options with values to hide elements

Time:06-07

I am looking at how to get an array of option elements from a select dropdown with the certain values and then I am going to hide them.

My HTML so far is:

<select>
<option value="1">1 AM</option>
<option value="2">2 AM</option>
<option value="3">3 AM</option>
<option value="4">4 AM</option>
<option value="5">5 AM</option>
<option value="6">6 AM</option>
<option value="7">7 AM</option>
<option value="8">8 AM</option>
<option value="9">9 AM</option>
</select>

What I want to do is get certain options with the values of certain numbers and hide those.
Should be simple enough.

The long winded way I was going to do it. Would be something like:

 $('option[value="1"],option[value="2"],option[value="3"],option[value="6"]').remove();

But that is not sustainable once I get a lot more values generated into the option list.

How would I create the array of elements I need with the values I need and then use the .remove() to remove the elements.

Thanks


UPDATE/EDIT - PART TWO OF QUESTION: (answered my own solution below)

Got this working using based on another solution [https://stackoverflow.com/questions/63804234/jquery-filter-select-options-by-array], works for the most part.... but see later below.

  var myArray = ["0800", "0805", "0810", "0815", "0820", "0825", "0830", "0835", "0840" ]; 
    // this goes by a step of 5 from 0800 to 1000
        $("#sessionStartTime option").filter(function () 
       {
           return $.inArray($(this).val(), testArray) > -1;
        }).remove();

That said, second part of a question than.

Would there be a way to get a range of times or a range of number and toss those into an array as the numbers. You will see the values I have are coming back of what I think are "octal". But in the return array it returns the numbers without the leading "0".

I have looked up a few ways of doing this but nothing seems to do what I need to. I thought about using a '.contains()' or something of the sort but not sure how to implement it. I don't have control over the values building the list because those come from a JSON call that populates the select option list.

This is what I have so far for my range but the leading zero gets omitted but the leading zero is NEEDED to filter the options. Based of this example [https://jasonwatmore.com/post/2021/10/02/vanilla-js-create-an-array-with-a-range-of-numbers-in-a-javascript]

const end = 1000;
        const start = 0800;
        const step = 5;
        const arrayLength = Math.floor(((end - start) / step))   1;
        var timeArray = [...Array(arrayLength).keys()].map(x => (x * step)   start);
        console.log("timeArray:"   timeArray);
   //Returns numbers without leading zeros but I need the leading zeros

CodePudding user response:

Here I will include a long verbose example and a short version. To wrap this all in an array, just put this in a function that you call, passing the array of values you wish to remove.

let excludeNumbers = [1, 4, 6, 8, 22];
var opts = $("#good-stuff")
  .find('option');
console.log(opts.length);
var found = opts.filter(function(idx, elem) {
  // console.log(idx, elem);
  let myval = this.value * 1; //faster than parse
  // console.log(myval);
  let isIt = excludeNumbers.includes(myval);
  console.log(isIt);
  return isIt;
});
console.log(opts.length, found.length);
found.remove();

// short form
$("#short-stuff")
  .find('option')
  .filter(function() {
    return excludeNumbers.includes(this.value * 1);
  }).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="good-stuff">
  <option value="1">1 AM</option>
  <option value="2">2 AM</option>
  <option value="3">3 AM</option>
  <option value="4">4 AM</option>
  <option value="5">5 AM</option>
  <option value="6">6 AM</option>
  <option value="7">7 AM</option>
  <option value="8">8 AM</option>
  <option value="9">9 AM</option>
</select>

<select id="short-stuff">
  <option value="1">1 AM</option>
  <option value="2">2 AM</option>
  <option value="3">3 AM</option>
  <option value="4">4 AM</option>
  <option value="5">5 AM</option>
  <option value="6">6 AM</option>
  <option value="7">7 AM</option>
  <option value="8">8 AM</option>
  <option value="9">9 AM</option>
</select>

Alternative version: Don't remove them just hide them by setting a value and let the CSS do the work.

let excludeNumbers = [1, 4, 6, 8, 22];

$("#good-stuff").on('hide-them', function(event, data) {
  $(this).find('option')
    .filter(function() {
      let t = data.a.includes(this.value * 1);
      let x = t ? "hide" : "show";
      this.dataset.isvisible = x;
      return !t;
    })
    // just to make the css work by changing the selected option
    .first().prop("selected", true);
});

$("#good-stuff").trigger('hide-them', [{
  "a": excludeNumbers
}]);

// now we trigger the new options:
$("#change-up").on('click', function() {
  $("#good-stuff").trigger('hide-them', [{
    "a": [3, 7, 8]
  }]);
});
.#good-stuff option {
  display: block;
}

#good-stuff option[data-isvisible="hide"] {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="good-stuff">
  <option value="1">1 AM</option>
  <option value="2">2 AM</option>
  <option value="3">3 AM</option>
  <option value="4">4 AM</option>
  <option value="5">5 AM</option>
  <option value="6">6 AM</option>
  <option value="7">7 AM</option>
  <option value="8">8 AM</option>
  <option value="9">9 AM</option>
</select>

<button id="change-up" type="button">Change them</button>

CodePudding user response:

If you have an Array of matching values Strings, use Array.prototype.includes

const hideHours = ["1", "2", "3", "6", "7"];

document.querySelectorAll("option")
  .forEach(el => el.hidden = hideHours.includes(el.value));
<select>
  <option value="1">1 AM</option>
  <option value="2">2 AM</option>
  <option value="3">3 AM</option>
  <option value="4">4 AM</option>
  <option value="5">5 AM</option>
  <option value="6">6 AM</option>
  <option value="7">7 AM</option>
  <option value="8">8 AM</option>
  <option value="9">9 AM</option>
</select>

just, make sure to be more specific with your selectors, so instead instead of document.querySelectorAll("option") try to target the specific Select Element by ID like document.querySelectorAll("#hours option")

CodePudding user response:

This is my answer I came up with. Thank for all the help.

// HTML
 <select id="sessionStartTime">
  <option value="0800">8:00 am</option>
<option value="0805">8:05 am</option>
<option value="0810">8:10 am</option>
<option value="0815">8:15 am</option>  
// .....ALL THE WAY UP TO 10:00 AM AND VALUE OF 1000
</select>


  //Javascript
           const end = 1000;
            const start = 0800;
            const step = 5;
            const arrayLength = Math.floor(((end - start) / step))   1;
            var timeArray = [...Array(arrayLength).keys()].map(x => (x * step)   start); //TODO: NEED TO GET THIS TO KEEP THE LEADING ZERO FOR REMOVAL
            console.log("timeArray:"   timeArray);
            var newTimeArr = [];
            $.each(timeArray, function (i, numb) {
                newTimeArr.push("0"   numb);//add the zero and push to new array
            });

            $("#sessionStartTime option").filter(function () {
                return $.inArray($(this).val(), newTimeArr) > -1;
            }).remove();
  • Related