当自定义属性NOT等于x </option>时,按.class AND删除<option>

时间:2014-05-22 12:07:11

标签: javascript jquery html

我拥有的:

我有一个选择元素。有些选项同时具有类(.filterable_option)和自定义属性(data-clienturn)。

我需要什么:

基于另一个元素的on change事件,我需要从select元素中删除选项:

  1. ...被归类为.filterable_option
  2. ...数据 - customattribute值不等于预定义变量(var = $some_value)的值。
  3. 我的代码:

    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:

    为方便起见:http://jsfiddle.net/clarusdignus/L82UH/

    我的问题:

    我的代码没有删除所需的选项。没有任何事情发生。

3 个答案:

答案 0 :(得分:5)

您在选择器中使用了一个名称。请改用ID,如下所示

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

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

或者,如果您仍想寻找姓名,请尝试以下代码:

$('select[name="myselect_a"]').on('change', function() {
  //your code 
});

答案 1 :(得分:4)

您选择了错误的选择器,并且还纠正了以下位: name='myselect_b']

演示:http://jsfiddle.net/aamir/L82UH/2/

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

答案 2 :(得分:1)

在标记中看到你有name属性:

<select name="myselect_a">

您正在使用ID选择器:

$('#myselect_a')

这就是问题所在。