简体   繁体   English

jQuery 或 Javascript 获取带有值的选择选项数组以隐藏元素

[英]jQuery or Javascript get array of select options with values to hide elements

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:到目前为止,我的 HTML 是:

<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.我将如何使用我需要的值创建我需要的元素数组,然后使用 .remove() 删除元素。

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.使用基于另一个解决方案 [https://stackoverflow.com/questions/63804234/jquery-filter-select-options-by-array] 的工作,大部分工作......但见下文。

  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".但在返回数组中,它返回不带前导“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.我考虑过使用 '.contains()' 或类似的东西,但不知道如何实现它。 I don't have control over the values building the list because those come from a JSON call that populates the select option list.我无法控制构建列表的值,因为这些值来自填充选择选项列表的 JSON 调用。

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]基于此示例 [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

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.替代版本:不要删除它们,只需通过设置一个值来隐藏它们并让 CSS 完成工作。

 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>

If you have an Array of matching values Strings, use Array.prototype.includes如果您有一个匹配值字符串的数组,请使用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")只是,请确保您的选择器更加具体,因此不要尝试使用document.querySelectorAll("option")来定位特定的 Select Element,例如document.querySelectorAll("#hours option")

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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