Variable retention on next click

2020-05-23 jquery

I have calendar table (calendar_tbl) and cells having date information. I also have 2 additional input date forms (start date and End Date). The selected dates on this table shall update the input date forms when blank and shall restart the update process when both the forms are updated once.

I am trying below code but the issue I am facing is that the variables d1_status and d2_status doesnt retain values.

jQuery("#calendar_tbl").find('td').click(function(){
    var selected_date=jQuery(this).attr('rel');
    var d1_status,d2_status;
    if(jQuery('#frontend_strt_date').val()==='' || (d1_status==1 && d2_status==1)){
        jQuery('#frontend_strt_date').val(selected_date);
        d1_status=1;
        d2_status=0;
    }
    else if(jQuery('#frontend_end_date').val()==='' || d2_status===0 ){
        jQuery('#frontend_end_date').val(selected_date);
        d1_status=1;
        d2_status=1;
    }
    console.log(selected_date);
    console.log(d1_status);
    console.log(d2_status);
});

Below is the console log when I select 3 dates in sequence: 2020-05-16, 2020-05-17 and 2020-05-18 2020-05-16. d1_status and d2_status are logged as undefined.

How to make these variables retained over next clicks?

2020-05-16
1
0
2020-05-17
1
1
2020-05-18
undefined
undefined

Answers

The problem here is : You already set var d1_status,d2_status; on each click that means if(d1_status == 1) or (d2_status === 0) doesn't get matched ever or it doesn't make any sense for the code while it keep remaining undefined and not updated on click

To avoid this .. Put cut/paste var d1_status,d2_status; outside/before the click event .. This way the variables will update on each click

var d1_status,d2_status;
jQuery("#calendar_tbl").find('td').click(function(){
    var selected_date=jQuery(this).attr('rel');
    if(jQuery('#frontend_strt_date').val()==='' || (d1_status==1 && d2_status==1)){
        jQuery('#frontend_strt_date').val(selected_date);
        d1_status=1;
        d2_status=0;
    }
    else if(jQuery('#frontend_end_date').val()==='' || d2_status===0 ){
        jQuery('#frontend_end_date').val(selected_date);
        d1_status=1;
        d2_status=1;
    }
    console.log(selected_date);
    console.log(d1_status);
    console.log(d2_status);
});

Related