问题
I have a Bootstrap modal where you can select a date. In the background, hidden fields are populated that are also submitted with the form.
The issue is that when you select the datepicker
element, it removes the hidden value for some strange reason (but only the hidden values populated by the Javascript).
Datepicker JS:
var date = new Date();
date.setDate(date.getDate());
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
startDate: date,
autoclose: true,
});
Hidden field Populating JS:
$(function () {
$('#appointment').on("show.bs.modal", function (e) {
$("#request_id").val($(e.relatedTarget).data('request-id'));
});
});
Hidden HTML element:
<input type="hidden" name="request_id" id="request_id" value="">
When the Modal box initially pops up, I can see the hidden value field is populated, but when I click the datepicker
, it's removed. Why is this?
回答1:
The issue is that show.bs.modal
is fired when bootstrap datepicker is opened. So you simply have to set #request_id
value only when the show.bs.modal
is related to modal opening. One way you can use to get the element that fired the event is checking e.target.id
value inside your handler.
Here a working sample:
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
startDate: new Date(),
autoclose: true,
});
$(function () {
$('#appointment').on("show.bs.modal", function (e) {
if( e.target.id == 'appointment'){
$("#request_id").val($(e.relatedTarget).data('request-id'));
}
});
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<input type="hidden" name="request_id" id="request_id" value="">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#appointment" data-request-id="myExampleId">
Open appointment modal
</button>
<div id="appointment" class='modal fade'>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class="modal-title">Title</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="datepicker">Date bootstrap</label>
<input type="text" id="datepicker">
</div>
</div>
</div>
</div>
</div>
回答2:
Use trusted Bootstrap-datepicker. If you using the same and making $ajax call, prevent extra values while making $ajax() by whilte listing your form values.
来源:https://stackoverflow.com/questions/42443566/javascript-added-html-value-is-removed-when-datepicker-is-selected