Nitz Nitz - 7 months ago 32
Javascript Question

How to run date picker on the first onclick event?

Hey Guys

I am using this date picker from jqueryui.

If you look on that page, then you will find that they have just written in one function like this:

$(function() {
$("#datepicker").datepicker();
});
</script>


But I want to open my date picker on one text box click event.

So I have written this:

$("#datepicker").datepicker();


in one function which I am calling on the textbox onclick event.

But in this there is one problem coming.


I am only getting the date picker on the second time I click on the text box.

If I click the first time after the page loads then the date picker will not come up but as soon as I click the second time then the date picker is coming.


Why? And can I do it on the first click?

Yes I know this is already happening perfectly if I put the first code but I want it in my function.

EDIT:

Now I will explain to all you guys what exactly I am doing.


My requirement is like this:


1) When I select the date the first time. Dates before today's date should be disabled in calender.

2) Now when I select the date the second time in the calender, the date should start one day after the previous date.


I have written like this....

$(function() {
$('#from').datepicker({
defaultDate: "+5d",
changeMonth: true,
numberOfMonths:1 ,
minDate:"+0d",
dateFormat: 'DD, MM d, yy',
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate";

var instance = $(this).data("datepicker");

var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);


dates.not(this).datepicker("option", option, date);

}
});

});


This works perfectly on one requirement,
but for the second requirement I need to check first if there is any text box value. If there is any then
it should select direct +1 to that date and previous dates should be disabled.


How to do this?

Answer

The reason it's not showing on the first click is because the instant you click it the first time, it is not registered as a datepicker. It therefore has no onclick event telling it that it should show any datepicker when you click it.

On the second click, however, you have set it as a datepicker during the first click (and it now has an onclick event where the datepicker will be shown). The datepicker's onclick event fires, showing the picker.

As mentioned in other answers, this is not the recommended way of doing it. But if you really want to bind it onclick and not onload, you can show the picker on the first click by doing

$(function() {
    $("#datepicker").click(function() {
        $(this).datepicker().datepicker( "show" )
    });
});

This will register the element as a datepicker and show then show it at the same time.