jquery datepicker - show week number if has specific class - javascript

I am using the jquery ui datepicker but I want to show the week number only if the input element has a specific class...
Here's what I've tried but with no success...
$(".myCal").datepicker({
showWeek: function(dateText, inst) { $(this).hasClass("showWeek"); }
});

As class selector is used, each method is required to iterate over all matching elements and then use $(this).
$(".myCal").each(function () {
$(this).datepicker({
showWeek: $(this).hasClass('showWeek')
});
});
http://jsfiddle.net/Ubw3L/5/

Can you try this
$(".myCal").datepicker({
showWeek: $(this).hasClass("showWeek");
});
As the API states, showWeek accept boolean value.

$('.myCal').each(function () {
$(this).datepicker({
showWeek: $(this).hasClass('showWeek');
});
});

Related

jQuery's datepicker not showing up after validation error [duplicate]

I have dynamically created textboxes, and I want each of them to be able to display a calendar on click. The code I am using is:
$(".datepicker_recurring_start" ).datepicker();
Which will only work on the first textbox, even though all my textboxes have a class called datepicker_recurring_start.
Your help is much appreciated!
here is the trick:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});​
DEMO
The $('...selector..').on('..event..', '...another-selector...', ...callback...); syntax means:
Add a listener to ...selector.. (the body in our example) for the event ..event.. ('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector... (.datepicker_recurring_start in our example) , apply the event handler ...callback... (the inline function in our example)
See http://api.jquery.com/on/ and especially the section about "delegated events"
For me below jquery worked:
changing "body" to document
$(document).on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
Thanks to skafandri
Note: make sure your id is different for each field
Excellent answer by skafandri +1
This is just updated to check for hasDatepicker class.
$('body').on('focus',".datepicker", function(){
if( $(this).hasClass('hasDatepicker') === false ) {
$(this).datepicker();
}
});
Make sure your element with the .date-picker class does NOT already have a hasDatepicker class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker(); will fail! Instead you need to do...
$myDatepicker.removeClass('hasDatepicker').datepicker();
You need to run the .datepicker(); again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
This was what worked for me (using jquery datepicker):
$('body').on('focus', '.datepicker', function() {
$(this).removeClass('hasDatepicker').datepicker();
});
The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
_.each(repeaterWrapper, function (repeaterItem, index) {
var jq_nodes = $(repeaterItem.addedNodes);
jq_nodes.each(function () {
// Date Picker
$(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
dateFormat: "dd MM, yy",
showAnim: "slideDown",
changeMonth: true,
numberOfMonths: 1
});
});
});
});
observerjQueryPlugins.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
$('body').on('focus',".my_date_picker", function(){
$(this).datepicker({
minDate: new Date(),
});
});
None of the other solutions worked for me. In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them. So none of the event solutions worked for some reason.
This is what finally worked:
$(document).on('changeDate',"#elementid", function(){
alert('event fired');
});
Hope this helps someone because this set me back a bit.
you can add the class .datepicker in a javascript function, to be able to dynamically change the input type
$("#ddlDefault").addClass("datepicker");
$(".datepicker").datetimepicker({ timepicker: false, format: 'd/m/Y', });
I have modified #skafandri answer to avoid re-apply the datepicker constructor to all inputs with .datepicker_recurring_start class.
Here's the HTML:
<div id="content"></div>
<button id="cmd">add a datepicker</button>
Here's the JS:
$('#cmd').click(function() {
var new_datepicker = $('<input type="text">').datepicker();
$('#content').append('<br>a datepicker ').append(new_datepicker);
});
here's a working demo
This is what worked for me on JQuery 1.3 and is showing on the first click/focus
function vincularDatePickers() {
$('.mostrar_calendario').live('click', function () {
$(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
});
}
this needs that your input have the class 'mostrar_calendario'
Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"
See more about the difference here http://api.jquery.com/live/
$( ".datepicker_recurring_start" ).each(function(){
$(this).datepicker({
dateFormat:"dd/mm/yy",
yearRange: '2000:2012',
changeYear: true,
changeMonth: true
});
});

How to get the selected date from jquery datepicker

I am using jquery datepicker to show a calendar.Now as per my requirement i want to get the date selected by the user in my jquery variable which i will use in my application but i am not able to get the date ..
Here is the code for datepciker
<div id="datepicker"></div>
and here i am trying to get the selected code..
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
var date = $(this).val();
alert(date);
}
});
});
But, I am not able to get the date ..Please help me ..Thanks..
This should do the trick
$(function() {
$("#datepicker").datepicker();
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
It's basic but here is a jsfiddle with it alerting the selected date when selected
update to change the date format
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
jsfiddle
3rd update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).val();
alert(selected);
}
});
});
I have used a little more of the native markup for datepicker ui here try this and see if you get the alert as you are after.
4th Update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).datepicker("getDate");
alert(selected);
}
});
});
The 4th method uses $(this).datepicker("getDate") instead of $(this).val() as $(this).datepicker("getDate") returns a date object and $(this).val() returns the date as a string.
Depending on your needs select which one is appropriate.
(Added 4th method and explanation of the difference after #TimothyC.Quinn commented that the getDate being the correct method)
Though, question is answered, for people who just want a date object or set a date with specific format. There is simple functions jQuery provides. Here's working jsfiddle
$( "#datepicker" ).datepicker({ dateFormat: "dd-mm-yy" });
$("#datepicker").datepicker('setDate', '10-03-2020');
// pass string of your format or Date() object
$("#datepicker").datepicker('getDate');
// returns Date() object
$("#another_datepicker").datepicker('setDate', $("#datepicker").datepicker('getDate'));
// pass string of your format or Date() object
Try
$("#datepicker").datepicker({
onSelect:function(selectedDate)
{
alert(selectedDate);
}
});
OR
$("#datepicker").datepicker({
onSelect:function (dateText, inst)
{
alert(inst);
}
});
try this
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
})
you have two elements with the class .datepicker, the selector won't know which element to choose from. So, you'll have to specify the name of the input you're trying to get the date from
first = $(".datepicker[name=datepicker1]").datepicker('getDate');
second = $(".datepicker[name=datepicker2]").datepicker('getDate');
You can use the changeDate event outlined here instead of onSelect and then reference e.date or e.dates. See the JSON below.
HTML:
<div id='QA'></div>
<div id='datepicker'></div>
JS:
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({
clearBtn: true,
todayHighlight: false,
multidate: true
}) .on('changeDate', function(e){
$('#QA').html(JSON.stringify(e));
});
});
/*
{
"type":"changeDate",
"date":"2015-08-08T07:00:00.000Z",
"dates":[
"2015-08-08T07:00:00.000Z"
],
"timeStamp":1438803681861,
"jQuery21409071635671425611":true,
"isTrigger":3,
"namespace":"",
"namespace_re":null,
"target":{
},
"delegateTarget":{
},
"currentTarget":{
},
"handleObj":{
"type":"changeDate",
"origType":"changeDate",
"guid":52,
"namespace":""
}
}
*/
</script>
The ideal way is to get the date and convert it to a common format and utilize the same. (may passing to server or so.)
$("#datepicker").datepicker('getDate').toISOString()
so it will get the date in ISO stander.
All code is for Bootstrap Datepicker
var calendar = $('#calendar').datepicker("getDate"); // Ex: Tue Jun 29 2021 00:00:00 GMT+0600 (Bangladesh Standard Time)
or
var calendar = $('#calendar').data('datepicker').getFormattedDate('yyyy-mm-dd'); // Ex: 2021-06-30
if(calendar){
alert(calendar);
} else {
alert('null');
}
If you need it in specific format like '2021/09/28':
$.datepicker.formatDate('yy/mm/dd',
$('.date-picker-2').datepicker("getDate")
);
Here is how to get Date object from datepicker in the onSelect event:
$("#datepickerid").datepicker({
onSelect: function (dateText, inst) {
var date_obj = $(this).datepicker('getDate');
}
});
I find it strange that the onSelect caller would not return the date object by default.

How to get the year from datepicker ui?

I have code which the user choose date .
I need to to get the value year and put it in div.
How can I do that?
jsFissl Demo
many Thx.
the code:
<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
</div>
<div id="Year"></div>
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true
});
$("#Year").text($("#datepicker").val());
I try to use .substring(0, 4)but I don't kno how.
You can convert that input value into a Javascript Date as well and have everything from it's method.
http://jsbin.com/ugaxob/2/edit
$(".btn-getdate").click(function() {
var dt = $("#datepicker").val(),
d = new Date(dt);
$("#Year").text(d.getFullYear());
});
or go wild and use MomentJs plugin and you will get so much fun (live example updated)
When you want to perform something on a plugin, that is called act upon an event, and you should see the Events tab in the DatePicker, where you can find onSelect.
My live example was changed to act upon selection and no need to press any link or button.
This shows the year you wanted to extract.
HTML:
<meta charset="utf-8">
<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
<button>Show year</button>
</div><!-- End demo -->
JS:
$(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true
});
$("button").click(function() {
var split = $("#datepicker").val().split('/');
alert(split[2]);
});
});​
The split method of String class divides the string and returns as an array.
EDIT: This does everything you wanted.
Take a look at the onSelect event.
$(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
onSelect: function(dateText) {
var split = $("#datepicker").val().split('/');
$("#Year").text(split[2]);
}
});
});​
How about this : JSFiddle
No need to do string manipulation, just create Date object using selected date from datepicker and use getFullYear() method to get selected year...
$(function() {
$("#datepicker").datepicker({
onSelect: function(date) {
var d = new Date(date);
alert(d.getFullYear());
},
changeMonth: true,
changeYear: true
});
});

How to call a js function onSelect event of datepicker jquery?

Please anyone help me..
I have a js function
function updateAb(param){ some manipulation }
And i am calling a datepicker jquery onselect event like..
$( ".datepicker").datepicker({onSelect: function(dateText, inst) { ... }});
I want to call the js function in select, how to do that? My objective is to get the value onselect of date from the datepicker and setting the attribute value in input field. Can anyone help me???
Here goes ur code
$('.datepicker').datepicker({
dateFormat: 'dd-mm-yy',
numberOfMonths: 1,
onSelect: function(selected,evnt) {
updateAb(selected);
}
});
function updateAb(value){
$('#yourInputID').val(value);
}
$( ".datepicker").datepicker({
onSelect: function(dateText, inst) {
updateAb(dateText);
}
});
Even more simply, if you do want the dateText and inst parameters to be passed to updateAb
$( ".datepicker").datepicker({onSelect: updateAb});
$( ".datepicker").datepicker({
onSelect: function(dateText, inst) {
updateAb(dateText, inst);
}
});
In short
$( ".datepicker").datepicker({
onSelect: updateAb
});

putting datepicker() on dynamically created elements - JQuery/JQueryUI

I have dynamically created textboxes, and I want each of them to be able to display a calendar on click. The code I am using is:
$(".datepicker_recurring_start" ).datepicker();
Which will only work on the first textbox, even though all my textboxes have a class called datepicker_recurring_start.
Your help is much appreciated!
here is the trick:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});​
DEMO
The $('...selector..').on('..event..', '...another-selector...', ...callback...); syntax means:
Add a listener to ...selector.. (the body in our example) for the event ..event.. ('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector... (.datepicker_recurring_start in our example) , apply the event handler ...callback... (the inline function in our example)
See http://api.jquery.com/on/ and especially the section about "delegated events"
For me below jquery worked:
changing "body" to document
$(document).on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
Thanks to skafandri
Note: make sure your id is different for each field
Excellent answer by skafandri +1
This is just updated to check for hasDatepicker class.
$('body').on('focus',".datepicker", function(){
if( $(this).hasClass('hasDatepicker') === false ) {
$(this).datepicker();
}
});
Make sure your element with the .date-picker class does NOT already have a hasDatepicker class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker(); will fail! Instead you need to do...
$myDatepicker.removeClass('hasDatepicker').datepicker();
You need to run the .datepicker(); again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
This was what worked for me (using jquery datepicker):
$('body').on('focus', '.datepicker', function() {
$(this).removeClass('hasDatepicker').datepicker();
});
The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
_.each(repeaterWrapper, function (repeaterItem, index) {
var jq_nodes = $(repeaterItem.addedNodes);
jq_nodes.each(function () {
// Date Picker
$(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
dateFormat: "dd MM, yy",
showAnim: "slideDown",
changeMonth: true,
numberOfMonths: 1
});
});
});
});
observerjQueryPlugins.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
$('body').on('focus',".my_date_picker", function(){
$(this).datepicker({
minDate: new Date(),
});
});
None of the other solutions worked for me. In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them. So none of the event solutions worked for some reason.
This is what finally worked:
$(document).on('changeDate',"#elementid", function(){
alert('event fired');
});
Hope this helps someone because this set me back a bit.
you can add the class .datepicker in a javascript function, to be able to dynamically change the input type
$("#ddlDefault").addClass("datepicker");
$(".datepicker").datetimepicker({ timepicker: false, format: 'd/m/Y', });
I have modified #skafandri answer to avoid re-apply the datepicker constructor to all inputs with .datepicker_recurring_start class.
Here's the HTML:
<div id="content"></div>
<button id="cmd">add a datepicker</button>
Here's the JS:
$('#cmd').click(function() {
var new_datepicker = $('<input type="text">').datepicker();
$('#content').append('<br>a datepicker ').append(new_datepicker);
});
here's a working demo
This is what worked for me on JQuery 1.3 and is showing on the first click/focus
function vincularDatePickers() {
$('.mostrar_calendario').live('click', function () {
$(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
});
}
this needs that your input have the class 'mostrar_calendario'
Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"
See more about the difference here http://api.jquery.com/live/
$( ".datepicker_recurring_start" ).each(function(){
$(this).datepicker({
dateFormat:"dd/mm/yy",
yearRange: '2000:2012',
changeYear: true,
changeMonth: true
});
});

Categories