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

时间:2014-07-25 21:34:40

标签: javascript jquery html forms lightbox

我有一个用于存放表格的灯箱。有两个选择,选择英国或美国,每个选项都有自己的列表与之关联。

我已经在它工作的灯箱之外创建了这背后的逻辑,但是一旦加入它就失败了,当你选择任何一个国家时都没有切换到相关的选项?

Demo Fiddle

这是脚本,我也在使用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>

1 个答案:

答案 0 :(得分:0)

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();
});

当您保存对话框的结果时,您无法使用$(&#34; select.model&#34;)。您必须从此对象导航,例如

$("#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");
});