I want to set the data for two dates as start and end. It should be like this:
if the start month is 01, The end month must be 12 and end years must be the start year.
if the start month is not 01, The end month must be start month – 1 and end years must be the start year + 1.
for example:
start date: 2012/01 —–> end date: 2012/12
start date: 2012/02—–> end date: 2013/01
I tried this code:
<script defer>
$(document).ready(function () {
$("#datatable_years").DataTable();
$("#start_month_year").on('change',function (){
var year = $(this).val().trim()
var month = $("#start_month_month").val().trim()
if (year.length == 4){
if (!isNaN(year)){
$("#end_month_year").val(function(){
if(month== 0o1){
$("#end_month_year").val(parseInt(year))
}else{
$("#end_month_year").val(parseInt(year)+1)
}
})
}
}
})
$("#start_month_month").on('change',function (){
var month = $(this).val().trim()
if (month.length == 2){
if (!isNaN(month)){
if(month== 01){
$("#end_month_month").val(12)
$("#end_month_year").val(parseInt(year))
}else{
$("#end_month_month").val(month)
$("#end_month_year").val(parseInt(year)+1)
}
}
}
})
});
</script>
but the year does not complete right.
>Solution :
The variable year is not defined in the second event handler for start_month_month. You should make sure to retrieve it correctly.
You also need to handle the case where the year should be the same. Currently, you’re only handling the case where the year should be incremented.
$(document).ready(function () {
$("#datatable_years").DataTable();
$("#start_month_year").on('change', function () {
var year = $(this).val().trim();
var month = $("#start_month_month").val().trim();
if (year.length == 4) {
if (!isNaN(year)) {
$("#end_month_year").val(function () {
if (month == '01') {
return year;
} else {
return parseInt(year) + 1;
}
});
}
}
});
$("#start_month_month").on('change', function () {
var month = $(this).val().trim();
var year = $("#start_month_year").val().trim(); // Retrieve the year here
if (month.length == 2) {
if (!isNaN(month)) {
if (month == '01') {
$("#end_month_month").val('12');
$("#end_month_year").val(year); // Set the same year
} else {
$("#end_month_month").val(pad(parseInt(month) - 1, 2));
$("#end_month_year").val(parseInt(year) + 1);
}
}
}
});
});
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}