Jquery get year and month in separate selectbox - php

I have D.O.B select box in a form, I want to populate an exact days base on selected year and month
Year:
<select name="yy" id="yy" class="box">
<option value="2013">2013</option>
.
.
<option value="1955">1955</option>
</select>
Month:
<select name="mm" id="mm" class="box">
<option value="01">01</option>
.
.
<option value="12">12</option>
</select>
I will use PHP function to populate days:
function days_in_month($month, $year){
// calculate number of days in a month
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
In jQuery onchange, how could I get yy and mm values pass to days_in_month($month, $year) like below?
$('#mm').on('change', function() {
alert( this.value );
});
I don't want the page refresh for every onchange of selected values.

You can do this using javascript , no need to use ajax with php in this case :
<script type='text/javascript'>
function days_in_month(month, year){
// calculate number of days in a month
return month == 2 ? (year % 4 ? 28 : (year % 100 ? 29 : (year % 400 ? 28 : 29))) : ((month - 1) % 7 % 2 ? 30 : 31);
}
$(document).ready(function() {
$('#mm').change(function(){
var mm=$(this).val();//get the month
var yy=$('#yy').val();//get the day
$('#dd').val(days_in_month(mm,yy));// i assume that your input for day has id='dd'
});
});
</script>

Related

Leap year friendly year/month/day select option tags with PHP embedded

I'm trying to write codes with PHP to enable leap year friendly select option tags. For example, you pick a year, then it checks if it is a leap year or not, then it shows a pull down menu (select option tags) of days preceded by another select option tags of 12 months. PHP codes are embedded in HTML. Here is my failed attempt below (I'm new to PHP):
<form method="post">
<select name="year">
<option value="" selected>Pick a year</option><!--Default-->
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<select name="month">
<option value="" selected>Pick a month</option><!--Default-->
<!--Show all 12 months-->
<?php for( $i = 1; $i <= 12; $i++ ): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
<select name="day">
<option value="" selected>Pick a day</option><!--Default-->
<!--Show dates depending on the conditions below:-->
<?php
if ( $month == 1 || 3 || 5 || 7 || 8 || 10 || 12 )
{
//Show dates until 31
for ( $i = 1; $i <= 31; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
elseif ( $month == 2 )
{
//Leap year
if ( $year != "" && $year % 4 == 0 && $year % 100 == 0 && $year % 400 == 0 )
{
//Show dates until 29
for ( $i = 1; $i <= 29; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
//Regular year (Non-leap year)
else
{
//Show dates until 28
for ( $i = 1; $i <= 28; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
}
elseif ( $month == 4 || 6 || 9 || 11 )
{
//Show dates until 30
for ( $i = 1; $i <= 30; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
<input type="submit" value="submit">
</form>
Notes:
I understand that the above is the incomplete code and it doesn't work. Besides, I don't know how to define $year or $month or $day from the select tags. Should I do it like this? If so, where should I put it?
<?php
if( $_SERVER["REQUEST_METHOD"] == "POST" )
{
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
//The rest of the php code?
}
?>
Preferably, I do not want to show years by using for loops as in months and days. I would like to do it manually this time (sorry, but if you suggest I should use the for loop, I appreciate your advise).
I wrote $year =! "" in the leap year February if block because I want to evade the empty default values from being counted.
I warmly welcome your suggestions and corrections, please help me out :)
Thanks in advance!
As far as I know about leap year:
/**
* In the Gregorian calendar 3 criteria must be taken into account to identify leap years:
* 1. The year is evenly divisible by 4;
* 2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
* 3. The year is also evenly divisible by 400. Then it is a leap year.
*
* #param $year integer
* #return bool
*/
private static function isLeapYear($year)
{
// the rule was applied after 1582
if ($year > 1582) {
if (($year % 400 == 0 && $year % 100 != 0) || ($year % 4 == 0))
{
//"It is a leap year"
return true;
}
else
{
return false;
//"It is not a leap year"
}
}
return false;
}
This won't work:
( $month == 1 || 3 || 5 || 7 || 8 || 10 || 12 )
This will only check that $month == 1, then the other conditions will be evaluated to true because the integers are evaluated to true (and PHP can't compare a variable to booleans with this code).
It looks like you're trying to get the number of days per month. This can be done easily with DateTime::Format() that use the date() format:
t returns the Number of days in the given month:
$dt = new Datetime('2016-02-15');
print $dt->format('t');
// display "29"
Example.
L returns the 1 if a year is leap, 0 otherwise:
$dt = new Datetime('2016-02-15');
print $dt->format('L');
// display "1"
$dt = new Datetime('2015-02-15');
print $dt->format('L');
// display "0"
Example.
You should probably don't care about the inputs and display all the years, the 12 months and 31 days per month and check the date with checkdate() once the data have been submitted.

use of dropdown list PHP

i have two questions. this is my code (Iranian calender), the problem is when i want see results. all values of year and month and day showns as '$year' and 'month' and 'day'.
<?php
echo'<select dir="rtl" name="year">';
for($year=1388;$year<=1410;$year++)
{
echo '<option value="$year">$year</option>';
}
echo'</select>';
echo'<select dir="rtl" name="month">';
for($month=1;$month<=12;$month++)
{
echo '<option value="$month">$month</option>';
}
echo'</select>';
echo'<select dir="rtl" name="day">';
for($day=1;$day<=31;$day++)
{
echo '<option value="$day">$day</option>';
}
echo'</select>';
?>
second question:
and i need another thing. in Iranian calendar month 1 to 6 have 31 days and 7 to 12 have 30 days so i need a conditional expression when user choose month 1 to 6 show 31 days to choose and when user chooses month 7 to 121 show 30 days.
You use double quotes inside of single quotes so it will be rendered as string.
Make the changes accordingly:
From:
echo '<option value="$year">$year</option>';
To:
echo '<option value="'.$year.'">'.$year.'</option>';
echo '<option value="'.$month.'">'.$month.'</option>';
echo '<option value="'.$day.'">'.$day.'</option>';
EDIT (answer to your second question):
JSFIDDLE
First you need to give an id attribute to your select fields.
<select dir="rtl" name="month" id="month">
<select dir="rtl" name="day" id="day">
Then you need to add some JQuery code that checks if month is greater than 6 so it will remove the last option (only if days are 31). If month is equal of 6 or less then will add a new option (only if days are 30).
$('#month').on('change', function() {
var monthValue = $(this).val();
var dayOptions = $('#day option').size();
if (monthValue > 6 && monthValue <=12) {
if (dayOptions == 31) {
$("#day option:last").remove();
}
} else if (monthValue >= 1 && monthValue <= 6) {
if (dayOptions == 30) {
$('#day').append($('<option>', {
value: 31,
text: 31
}));
}
}
});
you need to use " or use concatenation with . with '
so this should be:
echo '<option value="$day">$day</option>';
this:
echo '<option value="' . $day . '">' . $day . '</option>';
or this:
echo "<option value=\"$day\">$day</option>";

calculate end date from duration

I have a duration drop down menu with options 'yearly/quarterly/monthly' and start date textbox with datepicker. There is another textbox end_date.
Based on the duration I need the end date when duration and start date is selected.
E.g.: Start date is 23-09-2015 and duration chosen is 3 months so, I need to display 23-12-2015.But I have no idea how to do that.
PHP (5.3+) has a neat class to help adding a duration to a date its called DateInterval. (it has many other nice interval features as well)
$date = new DateTime('2015-10-02');
$date->add(new DateInterval('P3M'));
echo $date->format('Y-m-d'); // 2016-01-02
In the example above i add 3 months to my date. You can do other more complex things like P4Y1M2D, which is 2 days, 1 month and 4 years....
See php doc for more information: DateInterval
For a tutorial go here: Add a duration or interval to a date
Try this. This is an example. I hope this will help.
<?php
$date = date("Y-m-d");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +3 month");
echo date("Y-m-d",$date);
?>
If you need to add months and date do like this
$date = strtotime(date("Y-m-d", strtotime($date)) . " +3 month 2 day");
use
$date = date_create('2015-09-30');
date_add($date, date_interval_create_from_date_string('3 Months'));
echo date_format($date, 'Y-m-d');
Please check this
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#start_date").removeClass('hasDatepicker').datepicker(
{
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
onSelect: function(selectedDate)
{
var d = new Date( selectedDate );
if($('.date_range').val() == 'Yearly')
{
d.setFullYear( d.getFullYear( ) + 1 );
}
if($('.date_range').val() == 'Quarterly')
{
d.setMonth( d.getMonth( ) + 3 );
}
if($('.date_range').val() == 'Monthly')
{
d.setMonth( d.getMonth( ) + 1 );
}
year = d.getFullYear();
month = ("0" + (d.getMonth() + 1)).slice(-2);
date = ("0" + d.getDate()).slice(-2);
end_date = year +'-'+month+'-'+date;
$('#end_date').val(end_date);
}
});
});
</script>
<select name="date_range" class="date_range">
<option value="None">Please select a date range</option>
<option value="Yearly">Yearly</option>
<option value="Quarterly">Quarterly</option>
<option value="Monthly">Monthly</option>
</select>
<p>Start Date</p>
<input type="text" name="start_date" id="start_date" />
<p>End Date</p>
<input type="text" name="end_date" id="end_date" />

Every year last four months color different from other months in php

I have calculate the employee experience(months) in joining date to current date. I want every **last four months in a year** (eg 9-12 and 21-24 and 33-36 etc....) employeeexperience have shown as different color.(php code)
First year calculation has no problem after the years the conditions is not satisfy the `above criteria.`
This is my code but i need satisfy above criteria.
if($months % 9 == 0 || $months % 10 == 0 || $months % 11 == 0 || $months % 12 == 0)
{
<span style="color:green;"><?php echo $u_tot_exp;?><span>
}
else
{
<span style="color:black;"><?php echo $u_tot_exp;?><span>
}
The problem is your misunderstanding of the modulus operator %. You're using $months % 11 == 0 to mean "if the month is the eleventh in a year", but that isn't what it means. It actually means "if the month is a multiple of eleven after the first month". So this means November one year (the eleventh month), then October the next (the 22nd) then September (the 33rd).
The effect multiplies with % 10 or % 9. If we assume that the first year is 2014, it will select the following months:
2014: September, October, November, December
2015: June, August, October, December
2016: March, June, September, December
The % operator works by calculating the remainder when the number on the left is divided by the number on the right. Since we're working in years, we always need to divide by 12. You then want to check if the number left over is between 3 (i.e. September) and 0 (i.e. December).
$monthsToGo = $months % 12; // months remaining in the year
if ($monthsToGo >= 3) { // i.e. after September
echo "<span style=\"color:green;\">$u_tot_exp<span>";
} else {
echo "<span style=\"color:black;\">$u_tot_exp<span>";
}
Note that I have also fixed the code that outputs your HTML.
**Finally i have get the result using this code.**
<?php
$currentDate = date("d-m-Y");
// joining_date is name of field in DB.
$date1 = date_create("".$u_joining_date.""); //
$date2 = date_create("".$currentDate."");
$diff12 = date_diff($date2, $date1);
$hub_days = $diff12->days;
$months = $diff12->m;
$years = $diff12->y;
$tot_months = (($years * 12) + $months);
//$monthsToGo = $months % 12;
// months remaining in the year
//$monthsmod = $monthsToGo % 10;
if ($tot_months != 0)
{
if($months % 9 == 0 || $months % 10 == 0 || $months % 11 == 0 || $months % 12 == 0)
{
?>
<span style="color:green;"><?php echo $tot_months;?>month(s)<span>
<?php
}
else
{
?>
<span style="color:black;"><?php echo $tot_months;?>month(s)<span>
<?php
}
}
?>

How to validate select with PHP?

How to validate day/month/year select with php? I red some topics about who to validate select with 2-3 or even 5-6 select options. I would know how to validate that kind of select. But in the case of, for exemple, month, there are 32 options. Or in the case of year option, the are 60-70 options. So im interested in whats the optimal way to do select validation when you have so much options?
For date it's actually relatively easy - you just use checkdate().
And for the other cases you could check if the value is within an expected range like:
if ($val >= min && $val <= max)
or, in case you have all the values in an array
if (in_array($val, $array_of_valid_values))
Validating selects is fairly trivial.
Year
Let's say you have a sequential range of years from 1960-2013.
Your HTML for the selects is:
<select name="year">
<option value="1960">1960</option>
...
<option value="2013">2013</option>
</select>
So, you know that your year has to fall in the range of 1960 to 2013:
$year = (int) $_POST["year"]);
if ($year < 1960 || $year > 2013) {
$validationPassed = false;
}
Simple enough to validate the year.
Month
Now that you know what year it is, you can find out if it is a leap year. However, that is only important for a single month, so first let's validate what month they selected:
<select name="month">
<option value="0">January</option>
...
<option value="11">December</option>
</select>
Once again, validation of the month is easy. We know it has to be a value between 0 and 11.
$month = (int) $_POST["month"];
if ($month < 0 || $month > 11) {
$validationPassed = false;
}
Day
Now we know the month and the year. to validate the selected day, we need to check the following criteria:
Is it a leap year?
Is it the month of the year with the extra day for the leap year? (February).
For a year to be a leap year, it has to be divisible by 400, or not divisible by 100 and divisible by 4:
function isLeapYear($year) {
if ($year % 400 == 0)
return true;
else if ($year % 100 == 0)
return false;
else if ($year % 4 == 0)
return true;
return false;
}
Now, we can check if it is a leap year or not. If it is a leap year, then we know we need to allow 1 extra day in February.
We make an array of days in each month:
$daysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
Then we get the amount of days in the current month:
$monthDays = $daysInMonth[$month];
If it is a leap year, we add a day to the total days in the month:
if ($month == 1 && isLeapYear($year)) //February
$monthDays++;
Finally, we can validate the day
$day = (int) $_POST["day"];
if ($day < 0 || $day > $monthDays) {
$validationPassed = false;
}
Now, all of this is basically encapsulated into the checkdate() function that was in the other answer below. So, to use checkdate() instead of all the code above, you could simply do the following:
HTML
(Note: checkdate() is not zero-based, so we start our days and months at 1 instead of 0.)
<form action="myphp.php" method="post">
<select name="day">
<option value="1">1</option>
...
<option value="31">31</option>
</select>
<select name="month">
<option value="1">1</option>
...
<option value="12">12</option>
</select>
<select name="year">
<option value="1960">1960</option>
...
<option value="2013">2013</option>
</select>
</form>
PHP
$day = (int) $_POST["day"];
$month = (int) $_POST["month"];
$year = (int) $_POST["year"];
$validationPassed = checkdate($month, $day, $year);

Categories