动态选择选项在灯箱中失败

Dynamic select options failing in lightbox

本文关键字:失败 选择 选项 动态      更新时间:2023-09-26

我有一个用于容纳表单的灯箱。有两个选择,选择英国或美国,每个都有自己的列表关联到它。

我已经创建了这个背后的逻辑,但在灯箱之外,它可以工作,但是一旦添加进去,它就会失败,并且当您选择任何一个国家时,它不会切换到相关选项?

演示小提琴

这是脚本,我也使用lightbox featherlight。

 <select class="country">
    <option value="US">US</option>
    <option value="UK">UK</option>
</select>
<select class="model">
    <option></option>
</select>
<script>
$(document).ready(function() {
    var selectValues = {
        "UK": {
            "County1": "",
            "County2": ""
        },
        "US": {
            "State1": "",
            "State2": ""
        }
    };
    var $vendor = $('select.country');
    var $model = $('select.model');
    $vendor.change(function() {
        $model.empty().append(function() {
            var output = '';
            $.each(selectValues[$vendor.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });
    }).change();
});
</script>

Lightbox创建了一个div的副本。当您第一次加载对话框时,您必须将选择框的事件连接起来。幸运的是,您可以获得对刚刚打开的对话框的引用。

$("#openDialogButton").click(function () {
    var dlg = $.featherlight("#fl1",
        {
            otherClose: ".btn", //any .btn will close the dialog
            closeOnEsc: true
        }
    ); //open the featherlight dialog
    //FIND THE SELECT BOXES within the dialog you have just opened
    var $vendor = dlg.$content.find('select.country');
    var $model = dlg.$content.find('select.model');
    $vendor.change(function () { 
        $model.empty().append(function () {
            var output = '';
             $.each(selectValues[$vendor.val()], function (key, value) {
                 output += '<option>' + key + '</option>';
             });
             return output;
         });
     }).change();
});

当你保存对话框的结果时,你不能使用$("select.model")。你必须从这个对象开始导航,例如

$("#dialogOKButton").click(function () {
    var theCommentText = $("#commentText").val(); // null!
    theCommentText = $(
            $(this).parent()
        ).find("#commentText")
        .val(); // have to navigate from this
    alert("you entered this text " 
        + theCommentText + " and clicked OK");
});