4

我有一个如下所示的 select2 函数,

    function select2AutocompleteManyToManyField(field, request_url){
        var map = {};
        $("#"+field).select2({
            multiple: true,
            placeholder: field,
            minimumInputLength: 3,
            ajax: { // instead of writing the function to execute the request we use Select2's convenient helper

                url: request_url,
                dataType: 'json',
                data: function (term) {
                    return {
                        query: term
                    };
                },
            results: function (data) { // parse the results into the format expected by Select2.
                var objects = [];
                $.each(data,function(i,obj){
                    map[obj.translations__name] = obj;
                    objects.push({
                        "text": obj.translations__name,
                        'id': map[obj.translations__name].id

                    });
                });
                return {results: objects};
              }
            }
        });
}

我想用选定的字段 id 更新另一个隐藏字段的值。有没有办法做到这一点 ?

4

2 回答 2

3

我经历过这个,找不到解决方案。然后我在你的 sunbmit 点击填充隐藏字段

 $("#mysubmit").click(function () {
            $('#Hiddenfields').val($('#divforselect').val());
     });
于 2013-05-07T11:28:55.317 回答
2

这是我在这里某处看到并成功应用的方式:

            /* bind select2 */
            var select2 = $( '#city' ).select2({
                initSelection : function( element, callback ) {
                    var data = { id: element.val(), text: element.val() };
                    callback(data);
                },
                minimumInputLength: 2,
                ajax: {
                    url: "/city",
                    dataType: 'jsonp',
                    data: function( term, page ){
                            return {
                                q: term,
                                page_limit: 10
                        };
                    },
                    results: function( data, page ){
                        return { results: data.content.result };
                    }
                },
            }).data( 'select2' );
            select2.onSelect = ( function( fn ){
                return function( data, options ){
                    $( '#city_id' ).val( data.id );
                    return fn.apply( this, arguments )
                };
            })( select2.onSelect );
于 2013-05-07T11:21:53.213 回答