Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove <option> by .class AND when custom attribute NOT equal to x

What I have:

I have a select element. Some of the options have both a class (.filterable_option) and custom attribute (data-clienturn).

What I need:

Based on the on change event of another element, I need to remove options from the select element that:

  1. ...are classed as .filterable_option.
  2. ...have a data-customattribute value NOT EQUAL TO the value of a predefined variable (var = $some_value).

My code:

HTML:

<select name="myselect_a">
    <option selected="selected"></option>
    <option value="Apply filter">Apply filter</option>    
</select>

<select name="myselect_b">
    <option selected="selected"></option>
    <option data-customattribute="58" value="1" class="filterable_option">Dog</option>    
    <option data-customattribute="58" value="2" class="filterable_option">Cat</option>
    <option data-customattribute="60" value="3" class="filterable_option">Parrot</option>
    <option>I have no class or custom attribute.</option>
</select>

jQuery:

$('#myselect_a').on('change', function() {
    var $myselect_a_option = $("#myselect_a").val();
    if($myselect_a_option === 'Apply filter'){  
        var $some_value = '58';
        $("select[name=myselect_b] option.filterable_option[data-customattribute!=" + $some_value + "]").remove();
    }
});

JSFiddle:

For your convenience: http://jsfiddle.net/clarusdignus/L82UH/

My problem:

My code is not removing the required in options. Nothing happens.

like image 437
Clarus Dignus Avatar asked May 22 '14 12:05

Clarus Dignus


1 Answers

You have used a name in your selector. Use an id instead as shown below

<select id="myselect_a">
    <option selected="selected"></option>
    <option value="Apply filter">Apply filter</option>    
</select>

http://jsfiddle.net/L82UH/1/

Or if you still want to go for name, try the below code:

$('select[name="myselect_a"]').on('change', function() {
  //your code 
});
like image 196
Neel Avatar answered Oct 14 '22 05:10

Neel