I've been wrangling with this problem for over a week with little to no progress.
I've looked at
- How to set selected value of jquery select2?
- Select2 doesn't work when embedded in a bootstrap modal
- Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON
- Reset select2 value and show placeholder
- .
Finally, after looking at
I tried applying both the dropdownParent: $('#myModal')
and the
// 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. The populating is working correctly on all the elements (several of which are select / bo boxes) except the first bobox.
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">×</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 bo boxes):
@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:
<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 pletes 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 +
"\nment: " +
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>
I've been wrangling with this problem for over a week with little to no progress.
I've looked at
- How to set selected value of jquery select2?
- Select2 doesn't work when embedded in a bootstrap modal
- Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON
- Reset select2 value and show placeholder
- https://github./select2/select2/issues/3057
- https://github./select2/select2/issues/1436.
Finally, after looking at https://select2/troubleshooting/mon-problems
I tried applying both the dropdownParent: $('#myModal')
and the
// 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. The populating is working correctly on all the elements (several of which are select / bo boxes) except the first bobox.
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">×</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 bo boxes):
@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:
<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 pletes 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 +
"\nment: " +
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>
Share
Improve this question
edited Aug 7, 2018 at 17:01
Shiladitya
12.2k17 gold badges28 silver badges42 bronze badges
asked Aug 7, 2018 at 13:32
BeginnerOneBeginnerOne
911 silver badge10 bronze badges
1
- Possible duplicate of select2 display not updating label text but value is changing – Martin D. Commented Aug 7, 2019 at 17:21
1 Answer
Reset to default 6Okay, I think I came up with a fix found here: https://select2/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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744092419a4557325.html
评论列表(0条)