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

I had some help with some jQuery code for a form to create a cascading style dropdown. Select option in first dropdown and displays the relevant data in second dropdown.

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

The issue I am having is once the form is submitted, all data is inserted in to a database, and when I go to edit the form it should pull all data in relevant fields which is does for everything else except the second dropdown.

The first dropdown displays the correct pet_type which enables the second dropdown, but that is just empty with nothing.

Does the code need to be different or is it to do with something else?

Cheers

Well you have defined an onChange event listener with .change() but once the edit form is loaded, there is no actual onChange event happening (i guess your data comes pre-rendered in HTML). So you could trigger it manually by adding ("[name='pet_type']").trigger("change") to the end of your jQuery onLoad function.

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