Yii2:HTML选择只显示1行

zfciruhq  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(145)

我在Yii项目中的HTML选择有问题。我有隐藏的选择选项,在我选择国家后,区域选择选项显示为当前国家。选择只显示1行,当我在选择中向下滚动时,我可以看到国家的正确选项。
有人知道问题出在哪里吗?谢谢
下面是我的代码:
于飞:

<div class="form-group">
    <label class="control-label" for="region_id"><?= Yii::t('vo-card', 'Region') ?></label>
    <select class="form-control" name="region_id" id="select-region">
        <option value="" disabled selected><?= Yii::t('vo-card', 'Select') ?></option>
            <?php foreach ($region as $item) { ?>
                <option value="<?= $item->id ?>" data-country="<?= $item->id_cc_number_country ?>" hidden <?= $item->id == $request['region_id'] ? 'selected' : '' ?>><?= $item->region_name ?></option>
            <?php } ?>
    </select>
    <?php if (isset($errors['region_id'])) { ?>
        <div class="text-danger"><?= $errors['region_id'] ?></div>
    <?php } ?>
</div>

JavaScript语言:

$(document).on('change', '#select-country', function (event) {
    $('#select-region option:not(:disabled)').prop('hidden', true);
    $('#select-region option[data-country="' + $(this).val() + '"]').prop('hidden', false);

    $('#select-region option').prop('selected', function() {
        return this.defaultSelected;
    });

    event.preventDefault();
});

Here is the screen of my problem

yfjy0ee7

yfjy0ee71#

显然问题就出在这一行:

$('#select-region option[data-country="' + $(this).val() + '"]').prop('hidden', false);

注意事项:
$(this).val()-这是所选<option>value属性,但不是data-country属性的值。您需要通过data-country-filter选择所有<option>
下面是您的代码的更正版本:
https://jsfiddle.net/m5ayf9sx/

0aydgbwb

0aydgbwb2#

var arrRegions = [];

    $(document).ready(function(){
        arrRegions = $("#select-region").children();
    });

    $(document).on('change', '#select-country', function (event) {
        var country = $(this).val();
        $('#select-region option:not(:disabled)').remove();

        $(arrRegions).each(function(){
            if($(this).attr('data-country') == country){
                $('#select-region').append($(this));
            }
        });

        $('#select-region option').prop('selected', function() {
            return this.defaultSelected;
        });

        event.preventDefault();
    });

相关问题