Bootstrap 3 Datepicker Months View Only - asp.net-mvc

I have an ASP.NET MVC web app and trying to use Bootstrap 3 Datepicker for my "month/year" field like the one in demo here:
https://eonasdan.github.io/bootstrap-datetimepicker/#min-view-mode
In that demo, it only allows users to select "year" and "month". Not "days". I want the same functionality in my app. However, in my app, it works the same on first click but on succeeding clicks it shows the "days" selection view. Setting the viewMode to 'years' doesn't fix the problem.
My model is as follows:
public class FilterViewModel
{
public DateTime? StartMonthYear { get; set; }
...
My view is as follows:
<div class="col-sm-3">
#Html.TextBoxFor(model => model.StartMonthYear, new { #class = "month-picker" })
...
<script type="text/javascript">
$(function () {
$('.month-picker').datetimepicker({
viewMode: 'months',
format: 'MM/YYYY',
useCurrent: false
});
});
</script>

The problem is that viewMode only sets the initial view. However, it seems this particular library doesn't provide any way to actually restrict which views are available.
There's an alternate libary that I personally use, which does give you the ability. It's virtually a drop-in replacement, so you shouldn't have to change much to switch over. However, importantly, it provides minView/maxView options you can utilize:
$(function () {
$('.month-picker').datetimepicker({
startView: 'month',
minView: 'month',
format: 'mm/yyyy'
});
});
As you can see there's a few minor differences:
viewMode becomes startView. The view names are also singular month vs. months.
The formatting string is more similar to C# formatting, so you'd use lowercase mm and yyyy.
The default for this library is to use the current date/time, so there's no need for a separate useCurrent option. If you want to specify a different start date/time, you'd use initialDate.

I found a work around which works pretty well:
$(function () {
$('.month-picker').datetimepicker({
viewMode: 'months',
format: 'MM/YYYY',
useCurrent: false
});
$('.month-picker').on("dp.show", function (e) {
$(e.target).data("DateTimePicker").viewMode("months");
})
});
This is based on a reply found here.

This was a bug in the library and solved. I faced same problem and solved by simply downloading latest version.

Related

MVC - Get date with textbox

I want to take two date string with textbox or editor in mvc.
The format should be
"MM/yyyy-MM/yyyy".
I need to force the user for entering the input like above format without posting model.
#Html.TextBox("tbxDateRange", "", "{0:dd/MM/yyyy}", new { #class = "form-control dropdown", placeholder = "MM/yyyy - MM/yyyy" })
Above code not working event get just a formatted date string.
The format is working as expected. You are telling tbxDateRange's value (the zero in the third parameter ("{0:dd/MM/yyyy}") to format as day/month/year. It will therefore take the input in the text box and display it in that format.
It is only a display format. It will not enforce this format. For that you will need to do your own client side javascript (since you mentioned without posting the model). You could look at using a masked input element. ASP.NET MVC does not have a masked input out of the box.
You could use a masked input control like maskedinput which is a plugin for jQuery.
Additionally, you might want to look at breaking this up into two controls. One for the start and one for the end. You could consider using the html5 input type of date and you will automatically get a calendar. Although, if the day of the month will be too confusing for your users/UI then you could look at using jquery UI's datepicker and you can configure it to show only month and year.
Once you include jQuery UI in your app you would do something like jQuery UI DatePicker to show month year only.
In that example the winning answer formats the control in such a way to only show the month and year items of the control.
<script type="text/javascript">
$(function() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>

How to not show a mobile keyboard when using bootstrap-datepicker?

I tried setting the disableTouchKeyboard option but it did nothing -- at least on iOS/Safari. The options I was specifically using were:
$(".datepicker").datepicker({
autoclose: true,
disableTouchKeyboard: true,
format: 'm/d/yyyy',
startDate: '01/01/1900',
todayBtn: 'linked',
todayHighlight: true,
});
Anyone know what the best way to do this is?
If you are using Bootstrap3 Datepicker: https://eonasdan.github.io/bootstrap-datetimepicker
Just add this property to the input: readonly="readonly"
and this property to options when instantiate the library.
$('#datetimepicker1').datetimepicker({
useCurrent: false,
daysOfWeekDisabled: [0, 6],
format: 'DD-MM-YYYY',
ignoreReadonly: true <------ this property
});
Tested on Safari iPhone and Chrome / Native browser Android.
This is how I've accomplished this but I'd love to know if there are better ways.
Using the same options in the question, I then also made the HTML text box readonly by doing this in my HTML:
#Html.EditorFor(model => model.Date, new { htmlAttributes = new {
#class = "form-control datepicker", #readonly = "true",
}})
This seems to work as JavaScript can still change the value of the field. However, it does make the background of the text box gray (i.e., disabled) and it changes the mouse pointer to the crossed circle icon (not-allowed) which is not desired. To get around that I did this added an inline style:
#Html.EditorFor(model => model.Date, new { htmlAttributes = new {
#class = "form-control datepicker", #readonly = "true",
style = "cursor: default; background-color: #fff"
}})
I tried to override the cursor and background-color in CSS (using !important) but that didn't seem to work in Internet Explorer.
This isn't pretty but it works for me. Still need to see how I could do this in a more robust way (e.g., no hard coding the background color, not having to specify this on all of my date fields, etc.). If anyone knows a better way, I'd very much appreciate it.
I have/had a similar problem like this.
I use a input field type=text where i bind a jQuery datepicker to it. When I select the input field on my mobile (android chrome) I get the datepicker and the keyboard of the phone.
After searching StackOverflow I found some solutions about setting the input field on readonly or disabling the field. The problem with this is when you disable the field it will not be submitted, and when read-only is set my jQuery validator skips the field. So I needed a different solution.
I have now fixed it by letting the datepicker set the field on read only before opening the picker, and removing the readonly when the picker is closed. I have tested it so far on mobile android (chrome and I.E) and i dont get the native keyboard. iphone/ipad is not tested yet but maybe other can check it.
The code is:
$(this).datepicker({
beforeShow: function(input, obj){$(input).prop('readonly', 'readonly');},
onClose: function () {$(this).prop('readonly', false);}});
Just also add attribute readonly in datepicker.
$(".datepicker").datepicker({
format: "dd-M-yyyy",
autoclose: true,
disableTouchKeyboard: true,
Readonly: true
}).attr("readonly", "readonly");
This is an old question but I thought I should share my solution since this question shows up in Google search. If you make the input type a button the keyboard will not show up and you can style the button to look like a text input field if you really need to.
<input type="button" style="background-color:white;border:1px solid #DDD;padding:5px;cursor:text;" value="Enter a Date" id="datepicker">
This quick block of Javascript will allow you to disable keyboard input within Date fields. This snippet is helpful if you need to avoid the virtual keyboard from appearing within the datepicker.
<script type="text/javascript">
jQuery(function() {
jQuery( ".datepicker" ).datepicker({ }).attr('readonly','readonly');
});
</script>

MVC jquery MOBILE autocomplete - creates bullets not a drop down menu

I'm having an issue with autocomplete in jquery mobile. I want to create a text input that when the user inputs in it, the cities that correspond with what the user typed in shows up in a drop down menu, similar to how Google Search works.
My problem is that instead of a drop down menu, it just creates a bullet list of all the cities. I have the CSS theme implemented and all the necessary jquery/jquery mobile ui scripts enabled.
After watching the MVC pluralsight tutorial on MVC, I was able to connect to a database of city names and create the following code (these are just snippets):
View
<p>Hotel Location (City): <input type="text" data-autocomplete="#Url.Action("QuickSearch", "Booking")"/></p>
Javascript/Jquery
$(document).ready(function () {
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
});
Controller
public ActionResult QuickSearch(string term)
{
testautocompleteDataContext _db = new testautocompleteDataContext();
var cities = _db.CityTests
.Where(r => r.city.Contains(term))
.Take(10)
.Select(r => new { label = r.city });
return Json(cities, JsonRequestBehavior.AllowGet);
}
Thanks! I really appreciate the help :)
My mistake. I actually forgot to add jquery ui in my layout page! Stupid mistake hahaha

SetFoucsOnError in mVC

I am trying to set focus on the control while error occurs. I am use mvc 2.0. In Asp.net we have a property SetFoucsOnError but in MVC what is the substitute of it and how to implement ?
Well I did not get this solution. But i got an alternate option which even works :
$().ready(function() {
$("#Form").submit(function() {
$('.input-validation-error').focus();
$(".input-validation-error").each(function() {
$(this).focus();
});
});
});
I think the easiest way to do this is to use JavaScript.
The example uses jQuery and assumes controls with invalid data have a css class called input-validation-error:
$(function () {
$('form').submit(function() {
$(this).find('input.input-validation-error, select.input-validation-error')
.first()
.focus();
});
});
This will look for all input and select elements with the class input-validation-error, take the first of them and put the focus on it.

JQuery UI Multiselect how to get selected options values

wasted my day while searching how to get selected options values in JQuery UI widget by Michael Aufreiter. Here's the link to his demo site and github: http://quasipartikel.at/multiselect/
As a result I just need value fields of selected options without POST/GET sendings to PHP script.
I tried many methods and resultless.
Need your help and ideas
*Found many topics about jquery ui multiselect but useless because of Aufreiter :s *
That should work. Tested with Chrome console
$("#countries").val();
I went to the site you've got listed above, and was able to run this in my chrome console:
$('.ui-multiselect .selected li').each(function(idx,el){ console.log(el.title); });
It seems like the values you want are stored in the title attributes of the list items within the div.selected element.
Edit:
Doh! Well of course you want the values. Sorry mate. Completely missed that. The real goods are stored in the jQuery data() objects. In this case, the key you want is 'optionLink'. It maintains a reference to an option element. Each list item in the '.selected' div used the jQuery.data() method to add the underlying option to it.
So, you need to get the selected list items, iterate through, grab the 'optionLink' from the data jQuery data store, and then get the value.
The following code works on the example page:
$('.ui-multiselect .selected li').each(function(idx,el){
console.log(el);
var link = $(el).data('optionLink');
// link now points to a jQuery wrapped <option> tag
// I do a test on link first. not sure why, but one of them was undefined.
// however, I got all four values. So I'm not sure what the first <li>
// is. I'm thinking it's the header...
if(link){
// here's your value. add it to an array, or whatever you need to do.
console.log(link.val());
}
});
This is the first I've seen of the multiselect. It's slick. But I sympathize with your frustration trying to get something out. A 'getSelectedOptions()' method would be nice.
Cheers
Try accessing the selected values on the close event.
e.g.
$("#dropdown").multiselect({
header: false,
selectedList : 1,
height: "auto",
}).multiselectfilter().bind("multiselectclose", function(event, ui) {
var value = $("#dropdown").val();
});
Hope that helps.
Best solution
$('#select').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
height: "auto",
close: function() {
debugger;
var values = new Array();
$(this).multiselect("getChecked").each(function(index, item) {
values.push($(item).val());
});
$("input[id*=SelectedValues]").val(values.join(","));
}
});
You can try this:
$('#ListBoxId').multiselect({
isOpen: true,
keepOpen: true,
filter: true
});

Resources