I am taking on input tag that is calling a datepicker script for date. Now on onblur event of input tag, i am calling a javascript function that is working properly but on second time when i click on datepicker input for selecting value.
For the first time when i click on input tag and select a value from datepicker, nothing happens. But second time when i click on input tag and select a value from datepicker then my javascript function is working.
Here is the code:
// HTML code for input tag using datepicker script
<div class="input-append">
<input type="text" size="12" id="inputField" name="event_fromdate" readonly Placeholder="From Date" onblur="show_hide_fromdate();" />
</div>
// javascript function
function show_hide_fromdate()
{
var fromdate=$('#inputField').val();
var current_date = new Date();
var userdate = new Date(fromdate);
if(fromdate=="")
{
document.getElementById('msgFromDate').innerHTML = 'Enter From Date.';
}
else
{
if(current_date.getDate()>userdate.getDate() ||
current_date.getMonth()>userdate.getMonth() ||
current_date.getFullYear()>userdate.getFullYear())
{
document.getElementById('msgFromDate').innerHTML = 'Invalid event date';
}
else
{
$('#msgFromDate').html('');
}
}
}
Not getting the fault in this code.
I think that you problem is in onBlur
event. I don't know why you call JS method using onBlur
on readonly
textfield. Can you explain this?
This is happening because you onblur
events are not waiting for your datepicker
input. I think what you need is something which can tell you that the text in your textfield
has been changes. Something like this :
$("input[type=text]").change(function() {
alert("Text changed");
});
function show_hide_fromdate()
{
var fromdate=$('#inputField').val();
var current_date = new Date();
//comment this since first time this value of field is always empty
//I move it to validation part below
//var userdate = new Date(fromdate);
if(fromdate=="")
{
$('#msgFromDate').html('Enter From Date.');
}
else
{
var userdate = new Date(fromdate);
if(current_date.getDate()>userdate.getDate() ||
current_date.getMonth()>userdate.getMonth() ||
current_date.getFullYear()>userdate.getFullYear())
{
$('#msgFromDate').html('Invalid event date'.');
}
else
{
// maybe you should echo something to know whether it worked well or not to debug
$('#msgFromDate').html('Valid');
}
}
}
If above code does not work, you should use firebug to detect there has whether or not javascript error, maybe you should double check the output of datetime picker also. I recommend you add "console.log('on blur')" into function to debug how this event behavior works.