使用 JQuery 隐藏选择的选项

发布于 2024-10-12 04:05:55 字数 2409 浏览 3 评论 0原文

好的,让我们从一个例子开始。
请记住,这只是一个示例。

现在,我们有一个包含 3 个选项的下拉菜单。
我现在想做的是隐藏一个选项。

添加 style = "display:none"没有帮助。
该选项不会出现在下拉列表中,但使用箭头键,您仍然可以选择它。
本质上,它完全按照代码所述执行。它没有显示,就停在那里。

$("#1").hide() 的 JQuery 函数将不起作用。
另外,我不仅想隐藏该选项,还想完全删除它。

有这样做的可能性吗?

我必须使用父/同级/子元素吗?如果是这样,我仍然不确定如何。

一个相关的问题:我发现JQuery中有一个.remove()可用。效果很好。

但如果我想把它带回来怎么办?

如果(条件)
    {
   $(this).remove();
   }

我可以循环这个。不应该很复杂。
但我想做的是:

类的最大容量:(此处输入字段)
选择房间:(此处为下拉菜单)

我希望它做的是使用 .change().keyup 等函数更新 Dropdown >.
我只能在输入内容后创建下拉菜单。在更改或按键时,相应地执行下拉菜单。
但我正在做的是这样的:

$roomarray = mysql_query("选择 *
    来自
       (
      选择 *,
       案例
       当类型=“课堂”时,1
       WHEN type = '计算机实验室' THEN 2
       WHEN type = '演讲厅' THEN 3
       WHEN type = '礼堂' THEN 4
       END AS ClassTypeValue
       来自房间
       ) t
    ORDER BY ClassTypeValue, maxppl, roomID");

echo "<select id = \"room\">";
                    
while ($rooms = mysql_fetch_array($roomarray))
    { ?>
    <option value=<?php echo $rooms['roomID']; ?> id=<?php echo $rooms['roomID']; ?>><?php echo $rooms['type']; echo "&nbsp;"; echo $rooms['roomID']; echo "&nbsp;("; echo $rooms['maxppl']; echo ")"; ?></option>
    <?php
    }
                    
echo "</select>";

是的,我知道这很乱。我打算稍后更改它。

但现在的问题是:我可以切换选项的删除吗根据输入的内容

是否可以通过循环执行此操作?因为我肯定无法继续执行 SQL 查询,因为如果可能的话,我仍然认为它是可行的。一个坏的。

Okay, let's start with an example.
Keep in mind, this is only an example.

<select id = "selection1">
    <option value = "1" id = "1">Number 1</option>
    <option value = "2" id = "2">Number 2</option>
    <option value = "3" id = "3">Number 3</option>
</select>

Now from here, we have a dropdown with 3 options.
What I want to do now is to hide an option.

Adding style = "display:none" will not help.
The option would not appear in the dropdownlist, but using the arrow keys, you can still select it.
Essentially, it does exactly what the code says. It isn't displayed, and it stops there.

A JQuery function of $("#1").hide() will not work.
Plus, I don't only want to hide the option, I want to completely remove it.

Any possibility on doing so?

Do I have to use parent/sibling/child elements? If so, I'm still not sure how.

A related question: I found out that there is a .remove() available in JQuery. Works well.

But what if I want to bring it back?

if(condition)
    {
    $(this).remove();
    }

I can loops this. Shouldn't be complicated.
But the thing of which I am trying to do is this:

Maximum Capacity of Class: (Input field here)
Select Room: (Dropdown here)

What I'd like for it to do is to update is Dropdown using a function such as .change() or .keyup.
I could create the dropdown only after something is typed. At a change or a keyup, execute the dropdown accordingly.
But what I am doing is this:

$roomarray = mysql_query("SELECT *
    FROM
        (
        SELECT *,
        CASE
        WHEN type = 'Classroom' THEN 1
        WHEN type = 'Computer laboratory' THEN 2
        WHEN type = 'Lecture Hall' THEN 3
        WHEN type = 'Auditorium' THEN 4
        END AS ClassTypeValue
        FROM rooms
        ) t
    ORDER BY ClassTypeValue, maxppl, roomID");

echo "<select id = \"room\">";
                    
while ($rooms = mysql_fetch_array($roomarray))
    { ?>
    <option value=<?php echo $rooms['roomID']; ?> id=<?php echo $rooms['roomID']; ?>><?php echo $rooms['type']; echo " "; echo $rooms['roomID']; echo " ("; echo $rooms['maxppl']; echo ")"; ?></option>
    <?php
    }
                    
echo "</select>";

Yes, I know it is very messy. I plan to change it later on.

But the issue now is this: Can I toggle the removal of the options according to what has been typed?

Is it possible to do so with a dropdown made from a loop? Because I sure as hell can't keep executing SQL Queries. Or is that even an option? Because if it's possible, I still think it's a bad one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

动听の歌 2024-10-19 04:05:55

hide() 不适用于 Chrome...我一直在尝试一种解决方法并将其包装在一个名为“ExtraBox”的插件中。这个想法是临时存储选项,以便我们可以通过操作 DOM 来启用/禁用它们。我创建了该插件以使其更易于使用。

我已将代码发布在 jsFiddle 上,因此您可以自己尝试一下: http://jsfiddle.net/KeesCBakker/HaFRC/。 [注意:jsFiddle 中的第一个项目,我很喜欢它!]

Html 示例:

Select:
<br/>
<select id="TestKees">
    <option value="1" class="s1">First value</option>
    <option value="2" class="s2">Second value</option>
    <option value="3" class="s3">Third value</option>
</select>
<br/>
Enable / Disable
<br/>
<input id="txt" type="text" value="s2" />
<button id="btnEnable">Enable</button>

我已将以下 jQuery 添加到我的 document.ready 函数中:

$('#TestKees').extraBox({ attribute: 'class' });

$('#btnEnable').click(function(){
    $('#TestKees').data('extraBox').enable(
        $('#txt').val()
    );
});

$('#btnDisable').click(function(){
    $('#TestKees').data('extraBox').disable(
        $('#txt').val()
    );  
});

该插件如下所示:

(function($) {

    // Create ExtraBox object
    function ExtraBox(el, options) {

        // Default options for the plugin (configurable)
        this.defaults = {
            attribute: 'class'
        };
        // Combine default and options objects
        this.opts = $.extend({}, this.defaults, options);

        // Non-configurable variables
        this.$el = $(el);
        this.items = new Array();
    };

    // Separate functionality from object creation
    ExtraBox.prototype = {

        init: function() {
            var _this = this;
            $('option', this.$el).each(function(i, obj) {
                var $el = $(obj);
                $el.data('status', 'enabled');
                _this.items.push({
                    attribute: $el.attr(_this.opts.attribute),
                    $el: $el
                });
            });
        },
        disable: function(key){
            $.each(this.items, function(i, item){
                if(item.attribute == key){
                     item.$el.remove();
                     item.$el.data('status', 'disabled'); 
                } 
            });
        },
        enable: function(key){
            var _this = this;
            $.each(this.items, function(i, item){
                if(item.attribute == key){

                    var t = i + 1; 
                    while(true)
                    {
                        if(t < _this.items.length) {   
                            if(_this.items[t].$el.data('status') == 'enabled')  {
                                _this.items[t].$el.before(item.$el);
                                item.$el.data('status', 'enabled');
                                break;
                            }
                            else {
                               t++;
                            }   
                        }
                        else {                                                                               _this.$el.append(item.$el);
                            item.$el.data('status', 'enabled');
                            break;
                        }                   
                    }
                } 
            });     
        }
    };

    // The actual plugin - make sure to test
    // that the element actually exists.
    $.fn.extraBox = function(options) {

        if (this.length) {
            this.each(function() {
                var rev = new ExtraBox(this, options);
                rev.init();
                $(this).data('extraBox', rev);
            });
        }
    };
})(jQuery);

The hide() doesn't work for Chrome... I've been experimenting with a work-around and wrapped it in a plugin I called "ExtraBox". The idea is to store the options temporary so we can enable / disable them by manipulating the DOM. I've created the plugin to make it easier to use.

I've posted the code on jsFiddle, so you can try it for yourself: http://jsfiddle.net/KeesCBakker/HaFRC/. [note: first project in jsFiddle, I'm loving it!]

Html example:

Select:
<br/>
<select id="TestKees">
    <option value="1" class="s1">First value</option>
    <option value="2" class="s2">Second value</option>
    <option value="3" class="s3">Third value</option>
</select>
<br/>
Enable / Disable
<br/>
<input id="txt" type="text" value="s2" />
<button id="btnEnable">Enable</button>

I've added the following jQuery to my document.ready function:

$('#TestKees').extraBox({ attribute: 'class' });

$('#btnEnable').click(function(){
    $('#TestKees').data('extraBox').enable(
        $('#txt').val()
    );
});

$('#btnDisable').click(function(){
    $('#TestKees').data('extraBox').disable(
        $('#txt').val()
    );  
});

The plugin looks like this:

(function($) {

    // Create ExtraBox object
    function ExtraBox(el, options) {

        // Default options for the plugin (configurable)
        this.defaults = {
            attribute: 'class'
        };
        // Combine default and options objects
        this.opts = $.extend({}, this.defaults, options);

        // Non-configurable variables
        this.$el = $(el);
        this.items = new Array();
    };

    // Separate functionality from object creation
    ExtraBox.prototype = {

        init: function() {
            var _this = this;
            $('option', this.$el).each(function(i, obj) {
                var $el = $(obj);
                $el.data('status', 'enabled');
                _this.items.push({
                    attribute: $el.attr(_this.opts.attribute),
                    $el: $el
                });
            });
        },
        disable: function(key){
            $.each(this.items, function(i, item){
                if(item.attribute == key){
                     item.$el.remove();
                     item.$el.data('status', 'disabled'); 
                } 
            });
        },
        enable: function(key){
            var _this = this;
            $.each(this.items, function(i, item){
                if(item.attribute == key){

                    var t = i + 1; 
                    while(true)
                    {
                        if(t < _this.items.length) {   
                            if(_this.items[t].$el.data('status') == 'enabled')  {
                                _this.items[t].$el.before(item.$el);
                                item.$el.data('status', 'enabled');
                                break;
                            }
                            else {
                               t++;
                            }   
                        }
                        else {                                                                               _this.$el.append(item.$el);
                            item.$el.data('status', 'enabled');
                            break;
                        }                   
                    }
                } 
            });     
        }
    };

    // The actual plugin - make sure to test
    // that the element actually exists.
    $.fn.extraBox = function(options) {

        if (this.length) {
            this.each(function() {
                var rev = new ExtraBox(this, options);
                rev.init();
                $(this).data('extraBox', rev);
            });
        }
    };
})(jQuery);
醉南桥 2024-10-19 04:05:55

如果您只想删除元素,为什么要搞乱显示设置呢?

$('#1').remove();

它消失了。

Why are you messing around with display settings if you just want to remove the element?

$('#1').remove();

and its gone.

看轻我的陪伴 2024-10-19 04:05:55

据我所知,这是不可能的
原生地。您可以禁用
节点。至彻底
隐藏/删除它你需要写
一些自定义代码。

$('选项').attr('禁用', true);

顺便说一下,你不应该使用单个
数字作为元素的 ID。使用
某种前缀,即 option_1

实际上可以隐藏 节点,但不兼容跨浏览器。

As far as I know, this is not possible
natively. You can disable an
<option> node tho. To completlely
hide/remove it you would need to write
some custom code.

$('option').attr('disable', true);

By the way, you shouldn't use a single
number as an ID for an element. Use
somekind of prefix, i.e. option_1.

it actually is possible to hide an <option> node, but not cross-browser compatible.

困倦 2024-10-19 04:05:55

我想,你的选择器是错误的。尝试这样的操作(已更新):

<html>
    <head>
        <title>MooExample</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#click").click(function() {
                    $("#selection1 #1").remove();
                    //$("#selection1 > #1").toggle(); // Hide OR show
                });
            });
        </script>
    </head>

    <body>
        <select id="selection1">
            <option value="1" id="1">Number 1</option>
            <option value="2" id="2">Number 2</option>
            <option value="3" id="3">Number 3</option>
        </select>
        <input type="button" id="click" onclick="moo()" value="click" />
    </body>
</html>

请参阅父子选择器(父>子)。

I suppose, your selector is wrong. Try something like this (updated):

<html>
    <head>
        <title>MooExample</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#click").click(function() {
                    $("#selection1 #1").remove();
                    //$("#selection1 > #1").toggle(); // Hide OR show
                });
            });
        </script>
    </head>

    <body>
        <select id="selection1">
            <option value="1" id="1">Number 1</option>
            <option value="2" id="2">Number 2</option>
            <option value="3" id="3">Number 3</option>
        </select>
        <input type="button" id="click" onclick="moo()" value="click" />
    </body>
</html>

See parent-child selector (parent > child).

感情旳空白 2024-10-19 04:05:55

我已经提供了一个 jQuery 插件,可以很好地解决这个问题。有了它,您可以这样做:

$('#selection1').hideOption('1');
$('#selection1').showOption('1');

您可以根据需要隐藏和显示它们,并且它们将保持原始顺序。它适用于所有浏览器。您可以在此示例中看到: jsFiddle - 切换下拉选项

您可以获得 切换下拉选项插件。如果您不喜欢插件,只需将其中的 JavaScript 代码复制到您自己项目的 JavaScript 文件中即可。有关更多信息,请参阅插件上的阅读文档链接!

I've made available a jQuery Plugin that solves this very nicely. With it, you would do this:

$('#selection1').hideOption('1');
$('#selection1').showOption('1');

You can hide and show them as much as you want, and they will keep their original order. It works in all browsers. You can see that in this sample: jsFiddle - Toggle Dropdown Options

You can get the Toggle Dropdown Options plug-in. If you don't like plug-ins, just copy the JavaScript code from it to your own project's JavaScript file. See the Read the Docs link on the plug-in for more information!

迷路的信 2024-10-19 04:05:55

这在 Jquery 中非常简单

//For Hide
$('#selection1 option[value=1]').hide();

//For Show
$('#selection1 option[value=1]').show();

This Is Very Simple In Jquery

//For Hide
$('#selection1 option[value=1]').hide();

//For Show
$('#selection1 option[value=1]').show();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文