问题:
选择框的值为未设置的模态
但是当重新加载页面并打开模态时,它会设置选择框值。
预期:
在这两种情况下,选择框值都正确加载但未设置值。
jQuery:
function showModal() {
var selectbox_options = '<option value=""></option><option value="0"></option><option value="1"></option>';
//Above selectbox options are dynamically created using jquery each.
var selected_value = "0";
$('#modal').modal({
show: true,
backdrop: 'static',
keyboard: false
});
//I tried both by placing these below two lines above and inside show.bs.modal callbacks
$('#modal').on('shown.bs.modal', function(e) {
$('#modal').find(".dropdown-box").find('option').not(':first').remove();
$('#modal').find('.dropdown-box').append(selectbox_options).val(selected_value).trigger('change');
});
}
HTML:
<button type="button" onclick="showModal();"></button>
答案 0 :(得分:0)
检查一下,
您将值指定为selected_value
,但用作selectbox_value
此外,我也给出了选项值,以便识别选择框中的更改
function showModal() {
var selectbox_options = '<option value=""></option><option value="0">0</option><option value="1">1</option>';
//Above selectbox options are dynamically created using jquery each.
var selected_value = "0";
$('#modal').modal({
show: true,
backdrop: 'static',
keyboard: false
});
//I tried both by placing these below two lines above and inside show.bs.modal callbacks
$('#modal').on('shown.bs.modal', function(e) {
$('#modal').find(".dropdown-box").find('option').not(':first').remove();
$('#modal').find('.dropdown-box').append(selectbox_options).val(selected_value).trigger('change');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<button type="button" onclick="showModal();">open</button>
<div class="modal fade" id="modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<select class="dropdown-box"></select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>