【问题标题】:jQuery Select2 - Select ajax-submitted valuejQuery Select2 - 选择 ajax 提交的值
【发布时间】:2014-06-20 02:48:38
【问题描述】:

我有一个通过 ajax 提交新条目并返回条目数据的表单。我正在尝试在 Select2 字段中自动选择返回的数据。我可以获取输入的 id 作为输入值,但我不确定如何获取要在 span 中显示的文本。

这是我目前拥有的 JS:

function clientFormatResult(client){
    var markup = client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
    return markup; 
}

function clientFormatSelection(client) {
    $('#client-input').empty();
    $('#client-input').append('<input type="hidden" name="client" value="' + client.id + '" />');
    return client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
}

$('#client-selection').select2({
    placeholder: 'Select a client',
    allowClear: true,
    minimumInputLength: 1,
    ajax: {
        type: 'POST',
        url: 'clients/get_client_list',
        dataType: 'json',
        data: function (term) {
            return {filter: term};
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: clientFormatResult,
    formatSelection: clientFormatSelection,
    dropdownCssClass: 'bigdrop',
    initSelection: function (element, callback) {
        var id = element.val();
        if(id != '') {
            $.ajax('clients/get_client_list/'+id).done(function(data) {
                data = $.parseJSON(data);
                callback(data);
            });
        }
    }
});

$('#add-client-form').submit(function(e) {
    e.preventDefault();
    var form = $(this),
        url = form.attr('action'),
        data = form.serialize();
    $.post(url, data, function(data, status, xhr) {
        $('.form-response').fadeOut(400);
        if(status == 'success') {
            $('#add-client-modal').modal('hide');
            data = $.parseJSON(data);
            $('#client-selection').select2('val', data.client_id);
        } else {
            $('#add-client-failure').fadeIn(400);
        }
    });
});

如您所见,显示的文本类似于“John Smith (smithj)”。

【问题讨论】:

    标签: javascript php jquery ajax jquery-select2


    【解决方案1】:

    我整理出来了,这是我返回的数据的问题。 Select2 期待一个 id 变量,但我将其返回为 client_id。

    【讨论】:

      猜你喜欢
      • 2013-06-09
      • 1970-01-01
      • 2017-06-08
      • 2020-02-25
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      相关资源
      最近更新 更多