Monday, September 05, 2011

Jquery Datepicker - change Min Max dates on change of select box to values retrieved from mysql db

Using jquery datepicker, it is possible to restrict the date range available for selection
http://jqueryui.com/demos/datepicker/#min-max

I wanted the min and max dates to be dynamic variables based on mysql query results, that would change depending which value was selected in a select drop down.

To do this I created a php file that took the select drop down value and queried the database to return dates relevant to that value. Then outside the php tags, I put a javascript function, echoing the php variables as min max dates in two functions that could be called later using getscript().

Then all that is required is in the page where the datepicker is displayed, in the head section use .getscript() to get the variable jquery/javascript functions and apply them to various events, such as document.ready and .change of the select box value.

(The values of the select box are got using http://www.texotela.co.uk/code/jquery/select/ and passed as parameters on the url to the php script, where they are retrieved using $_GET['account'])

nb. The date needs to be correctly formatted, which can be done in the php code after retrieval from the db. The format of the date that is in the javascript function is like this:
YYYY, mm -1, dd
eg: 2011,01 -1 ,01



<script>
$(document).ready(function() {

var account = $("#accountselect").selectedValues();
$.getScript("restrictdates.php?account="+account+"", function() {minMax(); });


$('#accountselect').change(function() {
var account = $("#accountselect").selectedValues();
$.getScript("restrictdates.php?account="+account+"", function() {updateDate(); });
});

});

</script>

<select id="accountselect">
<option value="ac1">ac1</option>
<option value="ac1">ac1</option>
</select>

<input id="datepicker" type="text">



The restrictdates.php file is as follows...


<?php
$account=$_GET['account'];
//some php code here to retrieve specific $min and $max dates from database, for the relevant account
?>
function minMax() {
$("#datepicker" ).datepicker({
minDate: new Date(<?php echo $min; ?> ),
maxDate: new Date(<?php echo $max; ?>)
});
}

function updateDate() {
$( "#datepicker").datepicker('change',{
minDate: new Date(<?php echo $min; ?> ),
maxDate: new Date(<?php echo $max; ?>)
});
}


No comments: