简体   繁体   English

jQuery select2 的选择值未正确更新

[英]Select value of jQuery select2 not updating correctly

I've been wrangling with this problem for over a week with little to no progress.我一直在与这个问题争论一个多星期,几乎没有进展。

I've looked at我看过

Finally, after looking at https://select2.org/troubleshooting/common-problems最后,在查看https://select2.org/troubleshooting/common-problems 之后

I tried applying both the dropdownParent: $('#myModal') and the我尝试同时应用dropdownParent: $('#myModal')

// Do this before you initialize any of your modals
$.fn.modal.Constructor.prototype.enforceFocus = function() {};

Neither of these fixes worked so I'm really at my wits end and ready to give up on using the modal altogether.这些修复都没有奏效,所以我真的不知所措,准备完全放弃使用模态。 Basically I'm getting my data back from the server in a JSON object, then using that data to populate the modal.基本上,我从 JSON 对象中的服务器获取我的数据,然后使用该数据填充模态。 The populating is working correctly on all the elements (several of which are select / combo boxes) except the first combobox.除了第一个组合框外,填充对所有元素(其中几个是选择/组合框)都正常工作。

Thank you in advance for your help and sorry if the answer is posted elsewhere, but I can't find it.预先感谢您的帮助,如果答案张贴在其他地方,我很抱歉,但我找不到。 Following is the pertinent code:以下是相关代码:

<!-- Modal to Add / Edit Delay parent div must have same id as value of the data-target attribute used to trigger the modal -->
<div class="modal fade" id="delayAddModal" tabindex="-1" role="dialog" aria-labelledby="delayAddLabel">
    <div class="modal-dialog" role="document">
        <!-- Modal content -->
        <div class="modal-content">
            <div class="modal-header">
                <!-- This "x" button is for dismissing the modal -->
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                   <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="delayAddLabel">Add Delay</h4>
            </div>
            <div class="modal-body">
                <p id="testActualJobTaskIdFunction"></p>
                @Html.Partial("_ActualTrainDelayAddEdit", Model.TrainDelay)
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <!-- call to js function-->
                <button id="delayAddButton" type="button" class="btn btn-primary" data-title="Add Delay">Add Delay</button>
            </div>
        </div>
    </div>
</div>

Partial view nested in the modal defined above (this has been trimmed down so that the elements that are updating correctly are missing).嵌套在上面定义的模态中的部分视图(这已被修剪,以便正确更新的元素丢失)。 The subdivisionId is not updating correctly, however, locationId is (both are combo boxes): subdivisionId 没有正确更新,但是,locationId 是(都是组合框):

@model ActualTrainDelayAddEditModel

<form name="delay-form" id="delay-form">
    @Html.HiddenFor(m => m.ActualTrainDelayId, new { id = "ActualTrainDelayId" })

    @Html.HiddenFor(m => m.ActualJobTaskId)


    @*Original:*@
    <div class="form-group">
        <!-- Renders floating text ("Subdivision") above the select options -->
        @Html.LabelFor(m => m.SubdivisionId, new { @class = "field-label always-visible" })

        <!-- ID for select element -->
        <!-- Renders select class="select" id="SubdivisionId" name="SubdivisionId"><option value="4429faa8-5ad4-4adf-adde-ec7cf88ed9e9" innerHTML "Caltrain"-->
        @Html.DropDownListFor(m => m.SubdivisionId, Model.AvailableSubdivisions, new { @class = "select" })
        @Html.ValidationMessageFor(m => m.SubdivisionId)
    </div>

    <!-- Location -->
    <div class="form-group">
        @Html.LabelFor(m => m.LocationId, new { @class = "field-label always-visible" })
        <select id="LocationId" name="LocationId" class="select">
            @foreach (var loc in Model.AvailableLocations)
            {
                <option value="@loc.Id" data-milepost="@loc.Milepost">@loc.Name</option>
            }
        </select>

        @Html.ValidationMessageFor(m => m.LocationId)
    </div>
</div>

jQuery function that is updating the modal with the data:使用数据更新模态的 jQuery 函数:

<script>
// Do this before you initialize any of your modals
    $.fn.modal.Constructor.prototype.enforceFocus = function() {};

    $("#delayAddModal")
            .on("show.bs.modal",
                function(event) {
                    var button = $(event.relatedTarget); // Button that triggered the modal 
                    var modal = $(this);
                    var title = button.data('title'); // get New title from data-title attribute
                    var delId = button.data("guid");
                    var name = button.data("name");

                    var conditionalVariable = 1;

                    var updateButtonValue = "Save Edit";

                    //alert(title);


                    //$("#SubdivisionId").append("<option value='0'>--Select State--</option>");

                    //If add delay is clicked there will be no guid
                    if (delId == null) {

                        modal.find('.modal-title').text(title); // set title to Add Delay

                        modal.find('#delayAddButton').text("Add Delay"); // set button value to Add Delay
                        return;

                    }

                    modal.find('.modal-title').text(title); // set title to New title
                    modal.find('#delayAddButton').text(updateButtonValue); // set button value to Edit Delay

                    //    var button = $(event.relatedTarget);
                    //    var delId = button.data("guid");
                    //    var name = button.data("name");
                    //var modal = $(this);

                    $.ajax({
                        type: "GET",
                        url: "@Url.Action("GetDelayDataForEditing")/" + "?delayId=" + delId,
                        dataType: 'json',
                        //data: delId,
                        success: function(data) {


                            modal.find('');
                            //$("#SubdivisionId").change(function () {

                            var sub = data.SubdivisionId;

                            //console.log("This is the subId: "+sub);
                            //changing the subdivision changes the locations available in the location box
                            $.getJSON('@Url.Action("LocationBySubdivisionList", "TrainActivity")?id=' + sub,
                                function(locs) {

                                    // the stuff that needs to happen before the parent ajax completes needs to go in here
                                    $('#IncidentNumber').val(data.IncidentNumber);
    //                                    alert("In the getJson function");

                                    //$("select#SubdivisionId").empty();
                                    $('select#SubdivisionId').val(data.SubdivisionId);
                                    //$('#SubdivisionId').select2('data', data.SubdivisionId);
                                    //$('select#SubdivisionId').select2('data', data.SubdivisionId);
                                    //$('#SubdivisionId').select2('data', { id: 100, a_key: 'Lorem Ipsum' });
                                    $("#SubdivisionId > [value=" + data.SubdivisionId + "]")
                                        .insertBefore("#SubdivisionId > :first-child");
                                    //$("#SubdivisionId").append(data.SubdivisionId);

                                    $('#StartMilepost').val(data.StartMilepost);
                                    $('#EndMilepost').val(data.EndMilepost);


                                    var list = $('#LocationId');
                                    list.find('option').remove();
                                    $(locs).each(function(index, loc) {
                                        list.append('<option value="' +
                                            loc.Id +
                                            '" data-milepost="' +
                                            loc.Milepost +
                                            '">' +
                                            loc.Name +
                                            '</option>');
                                    });

                                    $('select#LocationId').val(data.LocationId);
                                    $("#LocationId > [value=" + data.LocationId + "]")
                                        .insertBefore("#LocationId > :first-child");
                                    //$("#LocationId").append(data.LocationId);
                                    //nearestMilepost();

                                    $('select#DelayTypeId').val(data.DelayTypeId);
                                    $("#DelayTypeId > [value=" + data.DelayTypeId + "]")
                                        .insertBefore("#DelayTypeId > :first-child");
                                    //$("#DelayTypeId").append(data.DelayTypeId);

                                    $('select#ThirdPartyResponsibleId').val(data.ThirdPartyResponsibleId);
                                    $("#ThirdPartyResponsibleId > [value=" + data.ThirdPartyResponsibleId + "]")
                                        .insertBefore("#ThirdPartyResponsibleId > :first-child");


                                    $('#BeginDelayDateTime').val(parseHoursAndMinutes(data.BeginDelayDateTime));
                                    $('#EndDelayDateTime').val(parseHoursAndMinutes(data.EndDelayDateTime));
                                    $('#ResultingDelay').val(data.ResultingDelay);
                                    $('#TimeInDelay').val(data.TimeInDelay);


                                    if (data.IsServiceFailure) {
                                        $('#IsServiceFailure').iCheck('check');
                                    } else {
                                        $('#IsServiceFailure').iCheck('uncheck');

                                    }

                                    if (data.IsResolved) {
                                        $('#IsResolved').iCheck('check');
                                    } else {
                                        $('#IsResolved').iCheck('uncheck');

                                    }

                                    if (data.IsRootCauseDelay) {
                                        $('#IsRootCauseDelay').iCheck('check');
                                    } else {
                                        $('#IsRootCauseDelay').iCheck('uncheck');

                                    }

                                    $('#Comment').val(data.Comment);

                                    $('#SavedVisible').iCheck('uncheck');

                                    $('#SaveNewComment').iCheck('uncheck');

                                    $('#ActualTrainDelayId').val(data.ActualTrainDelayId);

                                    //delayExists = true;
                                    //$('button#delayAddButton').attr("id", delId);

                                });

                            alert("Success " +
                                "\nunparsed data: " +
                                data +
                                "\nStringified data: " +
                                JSON.stringify(data) +
                                //"\nNew JS date: " + newJavaScriptDate +
                                //"\nDate date: " + parsedBeginDateTime +
                                //"\nFormatted date: " + hoursAndMinutes +
                                //"\nDisplay time: " + timeToDisplay +
                                //"\nAJT id: " + data.ActualJobTaskId +
                                //"\nIncident Number: " + data.IncidentNumber +
                                "\nLocation ID: " +
                                data.LocationId +
                                "\nStart MP: " +
                                data.StartMilepost +
                                "\nEnd MP: " +
                                data.EndMilepost +
                                "\nDelay Type Id: " +
                                data.DelayTypeId +
                                "\nThird Party Resp: " +
                                data.ThirdPartyResponsibleId +
                                "\nSubdivision Id: " +
                                data.SubdivisionId +
                                "\nbegin Delay time: " +
                                data.BeginDelayDateTime +
                                "\nend Delay time: " +
                                data.EndDelayDateTime +
                                "\nresulting delay: " +
                                data.ResultingDelay +
                                "\ntime in delay: " +
                                data.TimeInDelay +
                                "\nis root cause: " +
                                data.IsRootCauseDelay +
                                "\nis resolved: " +
                                data.IsResolved +
                                "\nis service failure: " +
                                data.IsServiceFailure +
                                "\ncomment: " +
                                data.Comment
                            );

                            //$('#delays-grid').data('kendoGrid').dataSource.read();
                            //$("#delayAddModal").modal("hide");


                        },
                        error: function() { alert("error in Delay Edit"); }
                    });


                    //modal.find(".modal-body").text("Edit the Delay at " + name + " with id " + delId);
                    //modal.find(".modal-footer #delayEditButton").data("guid", delId);
                });
</script>

Okay, I think I came up with a fix found here:https://select2.org/programmatic-control/add-select-clear-items好的,我想我想出了一个在这里找到的修复程序:https ://select2.org/programmatic-control/add-select-clear-items

I edited my statement from:我编辑了我的声明:

$('select#SubdivisionId').val(data.SubdivisionId);

to:到:

$('select#SubdivisionId').val(data.SubdivisionId).trigger('change');

Sorry for any inconvenience.任何不便敬请谅解。 Hopefully this helps.希望这会有所帮助。 Cheers.干杯。

Yes To apply change on edit value you should use: .trigger('change');是要对编辑值应用更改,您应该使用: .trigger('change'); at the end on setting value This save my day在设置值的最后这节省了我的一天

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM