过滤选择下拉框选项

时间:2014-01-06 21:21:48

标签: javascript jquery html

我正在尝试过滤掉一些下拉选择框,但是其中一个选项会出现一些奇怪的行为。

jsfiddle here

这是我正在使用的jQuery:

$(document).ready(function () {
$('select:gt(0)').find('option:gt(0)').hide().prop('disabled', true);

$('#C5R').change(function () {
    $('select:gt(0)').find('option:gt(0)').hide();
    var thisVal = $(this).val();
    if (thisVal == 1) {
        $('#C5T').find('option').each(function () {
            var thisVal = $(this).val();
            $(this).hide().prop('disabled', true);;
            if ((thisVal >= 1) && (thisVal <= 11)) {
                $(this).show().prop('disabled', false);;
            }
        });
    } else if (thisVal == 2) {
        $('#C5T').find('option').each(function () {
            var thisVal = $(this).val();
            $(this).hide().prop('disabled', true);;
            if ((thisVal >= 12) && (thisVal <= 32)) {
                $(this).show().prop('disabled', false);;
            }
        });
    } else if (thisVal == 3) {
        $('#C5T').find('option').each(function () {
            var thisVal = $(this).val();
            $(this).hide().prop('disabled', true);;
            if ((thisVal >= 33) && (thisVal <= 51)) {
                $(this).show().prop('disabled', false);;
            }
        });
    }
});
});

理论上它工作正常,第二个下拉列表在第一个上面进行过滤(我还没有对第3个过滤器进行编程,所以请忽略它)但是当选择Essex时(第3个选项)选项在第二个下拉列表中无法正确显示。实际下拉框无法正确呈现(在Chrome中,未在其他浏览器中测试)。

有没有人对此问题有解决方案/解决方法?

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是使用隐藏的select包含所有选项,并且只复制change上需要的选项

DEMO

<强> HTML

<select name="C5T" size="1" id="C5T" onchange="{C5TSelectChange(); onBlurUpdate(this)}" class="fontSize"></select>
<select id="C5Thidden" style="display:none">
    <option class="fontSize"></option>
    <option value="1" class="fontSize">Dereham</option>
    <option value="2" class="fontSize">East Dereham</option>
    ...
    <option value="51" class="fontSize">Witham</option>
</select>

<强>的jQuery

$(document).ready(function () {
    $('#C5R').change(function () {
        var thisVal = $(this).val();
        $C5T = $('#C5T');
        $C5T.empty();
        $options = $('option', '#C5Thidden');
        if (thisVal == 1) {
            filteredOptions = $options.slice(1, 12).clone();
            $C5T.append(filteredOptions);
        } else if (thisVal == 2) {
            filteredOptions = $options.slice(12, 33).clone();
            $C5T.append(filteredOptions);
        } else if (thisVal == 3) {
            filteredOptions = $options.slice(33).clone();
            $C5T.append(filteredOptions);
        }
    });
});