jquery function call on page both onload and onclick? - javascript

i am working on jquery calender but i need to call a function both on page load and then on click. when the page load for the first time it should automatically call and execute the function and for 2nd time and onward it should be call through click. is it possible?? if yes please help me.
<script type="text/javascript">
$(document).ready(function(){
$("#fullDate").datepicker({
showOn: "button",
buttonImage: "images/calender.jpg",
buttonImageOnly: true,
onClose: function(dateText, inst) {
$('#year').val(dateText.split('/')[2]);
$('#month').val(dateText.split('/')[0]);
$('#day').val(dateText.split('/')[1]);
}
});
});
</script>

Try writing a named function and call it on both events:
function doSomething() {
// ...
}
$(document).ready(function() { doSomething() });
$(yourElem).on("click", function() { doSomething() });
Alternatively to writing an anonymous function as a callback, just to call doSomething, you could also pass the function name as an argument, gaining a little performance by not cluttering memory with unnecessary anonymous functions:
$(document).ready(doSomething);
$(yourElem).on("click", doSomething);

$(document).ready(function(){
$("#fullDate").datepicker({
showOn: "button",
buttonImage: "images/calender.jpg",
buttonImageOnly: true,
onClose: function(dateText, inst) {
$('#year').val(dateText.split('/')[2]);
$('#month').val(dateText.split('/')[0]);
$('#day').val(dateText.split('/')[1]);
}
});
$("#fullDate").datepicker("show"); // this will run once.
});

During load, you can use
//when window loads
$(window).load(function(){
functionCallHere();
});
//or when DOM is ready
$(document).ready(function(){
functionCallHere();
});
Then for the click
$(element).click(function(){
functionCallHere(); //call the function again
});
Where functionCallHere is the name of the common function called on those events.

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
});
});

Call two functions on events

I´m trying to call two functions when closing the jQuery UI Datepicker, but I´m not sure what´s the best way to do this.
If I only have one function I can do this:
function splitArrivalDate() {
// Some code
}
$( '#mydatepicker' ).datepicker({
onClose: splitArrivalDate
});
But what if I want to call two functions sequentially on the onClose event?
function splitArrivalDate() {
// Some code
}
function setDepartureDate() {
// Some code
}
$( '#mydatepicker' ).datepicker({
onClose: splitArrivalDate; setDepartureDate // Does not work
});
I hope someone can help me understand this. Thanks!
You want something like this:
$( '#mydatepicker' ).datepicker({
onClose: function () { splitArrivalDate(); setDepartureDate(); }
});

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
});
});

jQueryUI datepicker - second instance flashes then disappears when show() is called

I have two jQueryUI datepickers on my page.
They're initialised as below:
jQuery("#departureDate").datepicker({
beforeShow: function() {
getDatesForCalendar("outbound");
},
numberOfMonths: 3,
constrainInput: true,
dateFormat: 'dd/mm/yy',
showButtonPanel: false,
hideIfNoPrevNext: true,
onSelect: function(dateText, inst) { jQuery('#returnDate').datepicker("show"); }
});
jQuery("#returnDate").datepicker({
beforeShow: function() {
getDatesForCalendar("return");
},
numberOfMonths: 3,
constrainInput: true,
dateFormat: 'dd/mm/yy',
showButtonPanel: false,
showOn: "focus",
hideIfNoPrevNext: true,
defaultDate: +1
});
Before they pop up they check which dates are available to them using getDatesForCalendar(), which contains no code that should hide or show the calendars.
My problem is that when the first calendar calls up the second (which is does onSelect), the second calendar flashes up for a second and then disappears. This is a FF/Chrome only issue, it doesn't appear to affect IE8.
I've tried a number of solutions including changing the tabindex (there is now none at all), disabling the show on focus functionality, and finally instead of manually calling datepicker("show") I've tried calling focus() on the field it's tied to. Nothing has worked!
Any advice would be greatly appreciated.
Many thanks,
Jack
Instead of showing the datepicker in the onSelect use the onClose event.
jQuery("#departureDate").datepicker({
numberOfMonths: 3,
constrainInput: true,
dateFormat: 'dd/mm/yy',
showButtonPanel: false,
hideIfNoPrevNext: true,
onClose:function()
{
jQuery('#returnDate').datepicker('show');
}
});
jQuery("#returnDate").datepicker({
numberOfMonths:3,
constrainInput: true,
dateFormat: 'dd/mm/yy',
showButtonPanel: false,
showOn: "focus",
hideIfNoPrevNext: true,
defaultDate: +1
});​
Looks like you will have to roll back to jquery ui 1.7.3 (loaded under Manage Resources in jsfiddle)
http://jsfiddle.net/6haqv/3/
Possible bug in jquery ui 1.8
I wanted to pop up second datepicker only if a date is selected in first one. If I use onClose, the second datepicker will show up even if did not select any date.
As work around to this problem I tried following and it works.
var checkin = $('#dpd1').datepicker({
minDate:now,
numberOfMonths:2,
showOn: "button",
buttonImage: "img/calender.png",
buttonImageOnly: true,
onSelect: function( selectedDate ) {
var dateObject=new Date(selectedDate);
dateObject.setDate(dateObject.getDate()+1);
$( "#dpd2" ).datepicker( "option", "minDate", dateObject );
showSecond=true;
},
onClose: function( selectedDate ) {
if(showSecond===true){
$( "#dpd2" ).datepicker("show");
showSecond=false;
}
}
});
I just got the same bug in jQuery UI 1.11.0.
I found a workaround by calling a setTimeout in the onSelect datepicker method:
$('#arrival-date, #departure-date').datepicker({
showAnim: 'slideDown',
onSelect: function(dateText, inst){
if($('#arrival-date').val() != '' && $(this).is('#arrival-date'))
{
setTimeout(function() {
$('#departure-date').datepicker('show');
}, 100);
}
}
});
Im not sure is that solution is good, did you saw what happen if you click on the first calendar, but you dont select any day, just simple click outside, and then try again to open it?
I try it and you can open the first calendar the first time, the second time you cant, you need to open the second calendar, and then you can again click on the first calendar.

Categories