Use jQuery DatePicker in Bootstrap 3 modal - jquery-ui

I would like to use jQuery UI datepicker in a modal. The real problem is that if I want to also show years and months, it shows me empty selects:
Using firebug, it seems that the option tags are under the modal.
This is my HTML:
<div class="modal-dialog">
<div class="modal-content">
<form id="add-form" action="#" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add</h4>
</div>
<div class="modal-body">
<div class="input-group">
<div class="input-group">
<label for="date">Date</label>
<input type="text" id="date" name="date" class="form-control datepicker"/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="submit" class="btn btn-primary">Salva</button>
</div>
</form>
</div>
</div>
Javascript:
$( ".datepicker" ).datepicker({
dateFormat: 'dd/mm/yy',
defaultDate: new Date(),
changeMonth: true,
changeYear: true
});
$('.datepicker').css("z-index","0");
I already tried this but it doesn't work (I have the same problem of giuseppe).

I found the solution with this answer. The only option you needed is enforceFocus.
Working Demo
jQuery
// Since confModal is essentially a nested modal it's enforceFocus method
// must be no-op'd or the following error results
// "Uncaught RangeError: Maximum call stack size exceeded"
// But then when the nested modal is hidden we reset modal.enforceFocus
$.fn.modal.Constructor.prototype.enforceFocus = function() {};

Only had to add this style:
<style>
.ui-datepicker{
z-index: 9999999 !important;
}
</style>

i could not get $.fn.modal.Constructor.prototype.enforceFocus = function() {}; to work becuase the 'focusin.bs.modal' event was already attached to the modal.
this is the code i got to work; because the date picker is called after the modal opens. using the beforeShow() and onClose function i was able to turn the focus event off and on
var datepicker_opts = {
changeMonth: true,
changeYear: true,
dateFormat: 'mm/dd/yy',
altFormat: "yymmdd",
setDate: new Date(),
maxDate: new Date()
};
BootboxContent = function(){
var frm_str = '<form id="some-form">'
+'<div class="form-group">'
+ '<label for="date">Date</label>'
+ '<input id="date" class="date span2 form-control input-sm" size="16" placeholder="mm/dd/yy" type="text">'
+ '</div>'
+ '</form>';
var object = $('<div/>').html(frm_str).contents();
object.find('.date').datepicker(
$.extend({
beforeShow: function(elem, inst) {
$(document).off('focusin.bs.modal');
},
onClose: function(selectedDate, inst) {
$modal = $(inst.input[0]).closest(".modal").data('bs.modal');
$modal.enforceFocus();
}
}, datepicker_opts)
);
return object
}
$('.add_date_btn').on('click', function () {
bootbox.dialog({
message: BootboxContent,
title: "View modal with date",
buttons: {
cancelar: {
label: "Cancel",
className: "btn-default"
}
}
});
}); //End click
.hidden-form #add_class_form {
display:none;
}
.ui-datepicker{
z-index: 9999999 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<button class="add_date_btn btn btn-primary btn-sm">View modal with date</button>

Related

Autocomplete in a modal is not listed/populated

I am creating an 'assign button' which calls a modal. In this modal will search a username queried from a database table. This autocomplete should be listed in the modal box, in fact it is not. I am using Jquery UI for this.
The "No search result" text is behind the modal, as well the assignee is listed behind the modal.
I am detailing my code in this jsfiddle
This is my original code:
$("#user_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
// url: "<?= site_url('Inventory/readuser'); ?>",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
console.log("response --> ", data);
response(data); //callback fn
}
}) //ajax
console.log("ok");
}, //source
select: function(event, ui) {
$('[name="username"]').val(ui.item.username);
$('[name="role"]').val(ui.item.role);
$('[name="location"]').val(ui.item.location);
}
}); //#user_name
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js" integrity="sha512-57oZ/vW8ANMjR/KQ6Be9v/+/h6bq9/l3f0Oc7vn6qMqyhvPd1cvKBRWWpzu0QoneImqr2SkmO4MSqU+RpHom3Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<i class="bx bxs-filter-alt text-white-50"></i>Assign
</div>
<div class="modal fade" id="updateUser" tabindex="-1" aria-labelledby="updateUser" aria-hidden="true">
<div class="modal-dialog modal-dialog-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Assign user ...</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<fieldset class="border rounded-3 p-2">
<legend class="float-none w-auto px-2 small">type a user name</legend>
<div class="frmSearch">
<input type="text" class="form-control form-control-sm" id="user_name" name="user_name" size="20" maxlength="3">
<div id="suggesstion-box"></div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-save-filter" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-save-filter" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
but in fiddle I am using dummy json from
https://dummyjson.com/docs/products
Please advise how to put the listed value into the green box in the modal.
Please review the following:
https://jsfiddle.net/Twisty/orv2j67n/1/
JavaScript
$("#user_name").autocomplete({
appendTo: "#suggestion-box",
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
}
});
console.log("ok");
},
select: function(event, ui) {
$('[name="label"]').val(ui.item.title);
}
});
Two changes to be aware of:
appendTo: "#suggestion-box",
Which element the menu should be appended to. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Regardless of the value, if no element is found, the menu will be appended to the body.
I also added a $.map() in the Success. This ensure that the proper elements exist when passing the data back to response().
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
This is discussed here: https://api.jqueryui.com/autocomplete/#option-source
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

stop bootstrap date-picker selecting today date

I've got a bootstrap date picker on my ruby on rails application but it keeps selecting today date as default how do I stop this?
Javascript
<script type="text/javascript">
$(".datepicker").attr('readOnly', 'true').css("background-color","white");
$(document).ready(function(){
$('.datepicker').datepicker({
"setDate": new Date(-70),
yearRange : '-70:-19',
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
autoclose: true});
});
</script>
As shown below today's date 30th march is selected. If the user doesn't change the year or month all dates for march in initial view will select for
"day March 2018"
Any help is much appreciated!
First of all, this is not a bootstrap datePicker this is jquery datePicker, see the below for bootstrap datePicker, for bootstrap datePicker you can use bootstrap datePicker gem, try to the following added to todayHighlight: false
$(document).ready(function() {
var dateInput = $('input[name="date"]'); // Our date input has the name "date"
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : 'body';
dateInput.datepicker({
"setDate": new Date(-70),
yearRange : '-70:-19',
dateFormat: 'dd/mm/yy',
todayHighlight: false,
changeMonth: true,
changeYear: true,
autoclose: true
});
$('#date').datepicker('setStartDate'); // <-- SO DOES THIS
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/css/tether.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<div class="bootstrap-iso">
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<form class="form-horizontal" method="post">
<div class="form-group ">
<div class="col-sm-10">
<input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text" />
</div>
</div>
</form>
</div>
</div>
</div>
</div>

how to show a jQuery ui DialogBox in ASP.NET MVC

I´m working on a MVC ASP.NET project and I would like to use a dialog box using jQuery ui every time a user clicks a specific button, was pretty easy for me in PHP but now in ASP.NEt I'm kinda stuck and cannot find the reason why, this is my code and the beginning of the page
#model GFC_Site.Models.UserModel.RegistroUser
#{
ViewBag.Title = "Registro";
}
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jqueryui")
#*I added the jquery, jquery ui and its due css via this way too in case the bundle created by myself has errors*#
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
<link href="~/Content/themes/base/dialog.css" rel="stylesheet" />
<link href="~/Content/themes/cupertino/jquery-ui.cupertino.min.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function ()
{
$("#submit").click(function () {
$("#dialog-confirm").dialog({
autoOpen: false,
resizable: false,
height: 170,
width: 350,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
},
buttons: {
"OK": function () {
$(this).dialog("close");
window.location.href = url;
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
});
</script>
and this is my form, it has more fields but I just show one, the button and the div I want to show
#using (Html.BeginForm("Registro", "Login", FormMethod.Post, new { #class = "form-horizontal", role = "form", id="nuevo" }))
{
#Html.AntiForgeryToken()
<div>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.NIT, new { #class = "sr-only control-label col-md-2" })
<div class="col-md-12">
<div class="input-group">
<div class="input-group-addon">digite NIT Proveedor</div>
#Html.TextBoxFor(model => model.NIT, new { #class = "form-control", #type = "text" })
</div>
<p class="text-danger"> #Html.ValidationMessageFor(model => model.NIT)</p>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" id="submit" value="Registrarse" class="btn btn-primary" #*onclick="return confirm('Desea ingresar información de registro?')"*# >
Registrarse
<span class="glyphicon glyphicon-user"></span>
</button>
</div>
</div>
</div>
<div id="dialog-confirm" style="display: none">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span> Are you sure to delete? </p>
</div>
}
Your razor view looks fine, but your JavaScript is only instantiating the dialog every time the submit button is clicked. If you want, you can move the dialog instantiation out of the submit click callback, and replace that with a $("#dialog-confirm").dialog("open"); call:
$(document).ready(function() {
// instantiate the dialog on document ready
$("#dialog-confirm").dialog({
autoOpen: false,
resizable: false,
height: 170,
width: 350,
show: {
effect: 'drop',
direction: 'up'
},
modal: true,
draggable: true,
open: function(event, ui) {
$(".ui-dialog-titlebar-close").hide();
},
buttons: {
"OK": function() {
$(this).dialog("close");
window.location.href = url;
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
$("#submit").click(function() {
// open the dialog on the submit button click
$('#dialog-confirm').dialog('open');
});
});

Restricting uib-datepicker to just one year

How do I fix the uib-datepicker to just one year. (say current year only).
I tried searching but all that I could find was to restrict calendar to year mode only. I tried setting year:2016 in datepicker-options but it didn't work.
Any suggestions ???
You can to use minDate and maxDate properties in the datepicker-options object as described in the docs.
The following code shows a datepicker limited to the current year:
angular.module('MyApp',['ui.bootstrap']).controller('AppCtrl', function($scope) {
$scope.open1 = function() {
$scope.popup1.opened = true;
};
$scope.dateOptions = {
minDate: moment().startOf('year').toDate(),
maxDate: moment().endOf('year').toDate()
};
$scope.format = 'dd-MMMM-yyyy';
$scope.popup1 = {
opened: false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-animate.min.js "></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-touch.min.js "></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.2.0/ui-bootstrap-tpls.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>
<div ng-app="MyApp" ng-controller="AppCtrl">
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" datepicker-options="dateOptions" show-button-bar="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
</div>
Note that I used moment startOf, endOf and toDate to get the first and the last days of the current year as Date objects.

Close ui-bootstrap modal with mouse click with no backdrop

I'm currently migrating ui-bootstrap from 0.5.0 to 0.14.3 (yep, I haven't checked for updates for that long). In 0.5.0 there was a 'modal' directive with the 'options' config object. There was a 'backdropClick' option, which allowed the modal to be closed when mouse-clicked outside of it. In 0.14.3 the $uibModal service doesn't have such option. It has a 'backdrop' property, which could be set to 'static', allowing you to close the modal with a mouse click, but the modal has a backdrop. And what if it hasn't? Could I close it with a mouse click with 'backdrop' property set to 'false'?
There is a workaround for this missing feature.
You can use a directive to detect a "click outside" event and then in the related event call the close modal method.
In the example below (adapted from ui.bootstrap docs) I used angular-click-outside directive:
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap','angular-click-outside']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $uibModal, $log, $document) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.animationsEnabled = true;
$document.on('click', function(event) {
});
$scope.open = function (size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
backdrop: false,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.0.3.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="//rawgit.com/IamAdamJowett/angular-click-outside/master/clickoutside.directive.js"></script>
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div id="my-modal" click-outside="cancel()">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
{{ item }}
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</div>
</script>
<button type="button" class="btn btn-default" ng-click="open()">Open me!</button>
<button type="button" class="btn btn-default" ng-click="open('lg')">Large modal</button>
<button type="button" class="btn btn-default" ng-click="open('sm')">Small modal</button>
<button type="button" class="btn btn-default" ng-click="toggleAnimation()">Toggle Animation ({{ animationsEnabled }})</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
</body>
</html>

Resources