You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jquery-editable-select后Django Select的onchange事件失效求解决

解决办法

问题根源是jquery-editable-select会将原生<select>元素隐藏,生成自定义的输入框和下拉结构,原生的onchange事件无法穿透到新结构上,必须使用插件提供的事件机制来绑定回调。

步骤1:移除原生select的onchange属性

修改forms.py里的组件定义,删掉attrs中的onchange属性:

class forms_bdc(forms.ModelForm):
    [...]
    bdc_description_1 = forms.ModelChoiceField(
        queryset=models_products.objects.values_list('product_denomination', flat=True),
        required=False, 
        widget=forms.Select(attrs={'id': 'editable-select-2'}),
        empty_label=None 
    )

步骤2:绑定插件的选择事件

在template.html的脚本中,替换原插件初始化代码,使用插件提供的回调或自定义事件触发你的populate_selected_product函数,两种方式任选其一:

方式一:初始化时传入onSelect回调

function populate_selected_product(product_selectbox_id, product_selectbox_value) {
    $.ajaxSetup({
        data: {
            product_num: product_selectbox_value,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
    });
    $.ajax({
        type: "GET",
        url: "../populate_selected_product/", 
        success: function (data) {
            $("#div_update_row_bdc_product").html(data)
            $('#'+product_selectbox_id).parent().find('#id_id_bdc').val($("#id_product_denomination").val())
        }
    });
}

// 初始化可搜索选择框并绑定选择事件
$('#editable-select-2').editableSelect({
    effects: 'fade',
    onSelect: function(element) {
        // 获取选中项的value值
        const selectedVal = element.val();
        populate_selected_product('editable-select-2', selectedVal);
    }
});

方式二:监听插件的自定义事件

function populate_selected_product(product_selectbox_id, product_selectbox_value) {
    $.ajaxSetup({
        data: {
            product_num: product_selectbox_value,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
    });
    $.ajax({
        type: "GET",
        url: "../populate_selected_product/", 
        success: function (data) {
            $("#div_update_row_bdc_product").html(data)
            $('#'+product_selectbox_id).parent().find('#id_id_bdc').val($("#id_product_denomination").val())
        }
    });
}

// 初始化插件
$('#editable-select-2').editableSelect({effects: 'fade'});

// 监听插件的选择事件
$('#editable-select-2').on('select.editable-select', function(e, element) {
    const selectedVal = element.val();
    populate_selected_product('editable-select-2', selectedVal);
});

这样就能在选择选项时正常触发你的AJAX逻辑了。

内容的提问来源于stack exchange,提问作者Nico44044

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 23:22:10