如何在Sweet Alert弹窗中使用DateTime Picker?
Integrating DateTimePicker into a SweetAlert Popup
Hey there! I see you're trying to add a DateTimePicker to your SweetAlert modal—great call for clean date/time input! Let's get this working smoothly step by step.
First, double-check you've got all required dependencies loaded:
- jQuery (since DateTimePicker relies on it)
- Your DateTimePicker library's CSS and JS files
The key trick here is initializing the DateTimePicker after the SweetAlert popup has fully rendered—since the input is dynamically added to the DOM, we can't initialize it before the alert is visible. Here's how to adjust your code:
swal({ title: "Confirm details?", text: '<input id="datetimepicker" class="form-control" autofocus>', type: "warning", customClass: 'swal-custom-width', html: true, showCancelButton: true, confirmButtonClass: "btn-success", confirmButtonText: "Confirm", cancelButtonText: "Cancel", closeOnConfirm: false, closeOnCancel: false, showLoaderOnConfirm: true, onOpen: function() { // Initialize DateTimePicker once the alert is open and the input exists $('#datetimepicker').datetimepicker({ format: 'YYYY-MM-DD HH:mm', // Adjust to your preferred date/time format minDate: new Date(), // Example: Block past dates step: 15, // Example: Set 15-minute time intervals // Add any other DateTimePicker config options you need here }); } });
Quick Notes:
- The
onOpencallback is critical here—it runs right after the modal is rendered, so the#datetimepickerelement is now in the DOM and ready to be initialized. - Tweak the
formatand other DateTimePicker settings to match your use case (like enabling/disabling time, setting date ranges, etc.). - Make sure your
swal-custom-widthclass has enough space to fit the DateTimePicker dropdown without layout glitches.
If you're using an older version of SweetAlert (v1.x) that doesn't support
onOpen, you can use theshowevent instead:swal({ // Your existing SweetAlert options }, function(isConfirm) { // Confirmation logic here }).then(function() { $('#datetimepicker').datetimepicker({ /* Your config */ }); });
内容的提问来源于stack exchange,提问作者Crazy
相关产品推荐
相关产品推荐

