Chris Ensell
Chris Ensell

Reputation: 153

JQuery- remove and add back certain options in a select

I have this select that is constantly changing (adding, removing, etc)...

It goes something like this:

<select class="validation" id="6401e0f3802aa3c1d76feca811b3c43c" name="attribute[75]">
<option value="109">Leather 1000</option>
<option value="111">Leather 2000 (+$300.00)</option>
<option value="112">Leather 3000 (+$400.00)</option>
<option value="113">Leather 5000 (+$500.00)</option>
</select>

I am using jQuery to strip out all the color options, which looks like this:

<select class="validation" id="" name="attribute[76]">
<option value="210">1000-Black</option>
<option value="211">2000-Black</option>
<option value="212">3000-Black</option>
<option value="213">5000-Black</option>
</select>

The number before the color corresponds with the leather type. My problem is that there are several hundred color options per leather type.

I am currently using this plugin:

(function($){

$.fn.extend({detachOptions: function(o) {
    var s = this;
    return s.each(function(){
        var d = s.data('selectOptions') || [];
        s.find(o).each(function() {
            d.push($(this).detach());
        });
        s.data('selectOptions', d);
    });
}, attachOptions: function(o) {
    var s = this;
    return s.each(function(){
        var d = s.data('selectOptions') || [];
        for (var i in d) {
            if (d[i].is(o)) {
                s.append(d[i]);
                console.log(d[i]);
                // TODO: remove option from data array
            }
        }
    });
}});   

})(jQuery);

To strip out all other options, including the colors. Currently I have fabric choices and colors working ok, but I need to remove and add only certain colors, and I need it to work automatically.

What I need to do is when Leather 1000 is selected, I need ONLY the color options that have 1000- in it.

Can anyone help me with this?

Upvotes: 0

Views: 2597

Answers (2)

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

here's an example: http://jsfiddle.net/8x7Cz/

be aware of the // tricky part you might want to change this

Upvotes: 2

aziz punjani
aziz punjani

Reputation: 25766

You can use the contains selector for your needs. Here's some very rough code to get your started.

$('select[name="attribute[76]"] option:contains("1000")')

Upvotes: 1

Related Questions