jQuery在编辑表单页面上没有加载数据

时间:2014-05-19 08:49:04

标签: javascript php jquery html

我对表单的一些jQuery代码有一些帮助,可以创建一个级联样式下拉列表。在第一个下拉列表中选择选项,并在第二个下拉列表中显示相关数据。

$(function () {
    window.all_options = $("[name='breed'] > option").detach(); // global variable

    $("[name='pet_type']").change(function () {
        var pet_type = $(this).val();
        $("[name='breed']").removeAttr("disabled").append(window.all_options);
        $("select[name='breed'] > option").each(function () {
            var o = $(this);
            if (o.data('pet-type') !== pet_type) {
            o.detach();
            }
        });
    });
});

我遇到的问题是,一旦表单被提交,所有数据都被插入到数据库中,当我去编辑表单时,它应该提取相关字段中的所有数据,除了第二个下拉列表之外的所有其他数据

第一个下拉列表显示正确的pet_type,它会启用第二个下拉菜单,但这只是空的,没有任何内容。

代码需要不同还是与其他东西有关?

干杯

1 个答案:

答案 0 :(得分:0)

你已经用.change()定义了一个onChange事件监听器,但是一旦加载了编辑表单,就没有实际的onChange事件发生(我猜你的数据是用HTML预渲染的)。因此,您可以通过将("[name='pet_type']").trigger("change")添加到jQuery onLoad函数的末尾来手动触发它。

$(function () {
    window.all_options = $("[name='breed'] > option").detach(); // global variable

    $("[name='pet_type']").change(function () {
        var pet_type = $(this).val();
        $("[name='breed']").removeAttr("disabled").append(window.all_options);
        $("select[name='breed'] > option").each(function () {
            var o = $(this);
            if (o.data('pet-type') !== pet_type) {
            o.detach();
            }
        });
    });

    $("[name='pet_type']").trigger("change");
});