7

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 "&nbsp;"; echo $rooms['roomID']; echo "&nbsp;("; 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.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
rollin340
  • 358
  • 2
  • 7
  • 19
  • BTW: ..is not valid to have an id or class name beginning with a number - see http://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-names – zack Jan 15 '11 at 12:11
  • I've changed the answer into a plugin that support disable (remove) and enable (append) of the options. I hope it answers your question(s). – Kees C. Bakker Jan 16 '11 at 14:14

6 Answers6

7

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);
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
3

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

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

and its gone.

fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
1

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!

Glen Little
  • 6,951
  • 4
  • 46
  • 68
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.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • So, for `$("option")`. this is changed to an ID tag or...? – rollin340 Jan 15 '11 at 11:56
  • @SyedAbdulRahman: `$('option')` would grab all `option` elements. This was just meant as example. You still would need to query for a specific element. – jAndy Jan 15 '11 at 11:58
  • So I could have a `function()` with an `if()` statement to select the specific elements, followed by a `$(this)`. From there I could use the `attr('disable', true);? – rollin340 Jan 15 '11 at 12:02
  • @SyedAbdulRahman: I updated my answer, you can just use `.hide()` as expected. – jAndy Jan 15 '11 at 12:05
  • @jAndy Yeah, had a typo. It won't work. The problem is that it's a HTML hardcode. The option will appear, even if hidden. – rollin340 Jan 15 '11 at 12:13
  • This won't work (hiding the option) cross-browser, make sure to test across the board ;) – Nick Craver Jan 15 '11 at 12:15
  • @NickCraver: yay I knew there were some issues. Worked fine in FF, probably a little hasty. So, the striked-out section is not that wrong at all. – jAndy Jan 15 '11 at 12:22
1

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).

shybovycha
  • 11,556
  • 6
  • 52
  • 82
  • Ah, parent-child seems simple now. Thanks. But I still can't hide it. – rollin340 Jan 15 '11 at 12:11
  • No. Same as the answer from jAndy, the `hide()` will not work for my ` – rollin340 Jan 15 '11 at 12:13
  • i've created a blank .html file and pasted my code there - works just perfectly. maybe you're using some strange version of jq? or your other js code is wrong? – shybovycha Jan 15 '11 at 12:16
  • I tested this using IE, Firefox and Opera. It only seems to work on FF. But even when hidden, it acts just as `style = "display:none"`. You can't see it, but you can always select it. – rollin340 Jan 15 '11 at 12:25
  • i've updated code. remove() works on chrome, ie and ff as well. – shybovycha Jan 15 '11 at 12:32
  • What the, there is a `remove()` function? I never knew that. This works. It works great. But umm....what if I want it to come back? WIll a `add()` work? Because I thought the `add()` requires a bound field after it. – rollin340 Jan 15 '11 at 12:38
  • I think there is no .add() manipulator. Use .before(), .after() or .append() ones: $("#selection1 #2").before(""); – shybovycha Jan 15 '11 at 12:44
0

This Is Very Simple In Jquery

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

//For Show
$('#selection1 option[value=1]').show();
Manoj Thapliyal
  • 567
  • 7
  • 9