Checkbox and datepicker

1

I'm looking for the way that when the checkbox flages change the format of the datepicker. This is my Jquery code

$(document).on('click','#chk_out',function ()
{
    if ($('#chk_out').is(':checked'))
    {
        $( ".datepicker" ).datepicker({ minDate: "-15D", maxDate: "+0D" });
        $( ".datepicker" ).datepicker( "option", "dateFormat","yy-mm-dd");
    }

    else
    {
        $( ".datepicker" ).datepicker({ minDate: "-1D", maxDate: "+0D" });
        $( ".datepicker" ).datepicker( "option", "dateFormat","yy-mm-dd");
    }
});

This is the HTML code

<div class="form-group">
            <h5>Incidencia extemporánea</h5><input type="checkbox" name="chk_out" id="chk_out" class="">
            </div>

            <div class="form-group">
            <h5>Fecha del incidente</h5>
              <input type="text" id="fecha" class="datepicker" readonly>
            </div>

Is not doing it, can you support me? Thank you. I did this fiddle link When the checkbox is checked you should enable me 15 days ago

    
asked by Alberto Siurob 22.12.2016 в 00:43
source

1 answer

5

Review this example, I'll explain it to you:

First in $(document).ready Initialize from the beginning the datepicker , then right there in $(document).ready add the function $('#chk_out').change , the trick to make it work is that you have to destroy the datepicker each time the checkbox change and rebuild the datepicker control with the new conditions.

 $(document).ready(function(){
	 
	$(".datepicker").datepicker({
		  minDate: "-1D",
		  maxDate: "+0D",
		  dateFormat: "yy-mm-dd"
	});
		
	$('#chk_out').change(function() {	
	  $(".datepicker").datepicker('destroy');
	  if ($('#chk_out').is(':checked')) {
		console.log('menos 15 dias');
		$(".datepicker").datepicker({
			  minDate: "-15D",
			  maxDate: "+0D",
			  dateFormat: "yy-mm-dd"
		});
	  } else {
		console.log('menos 1 dia');
		$(".datepicker").datepicker({
			  minDate: "-1D",
			  maxDate: "+0D",
			  dateFormat: "yy-mm-dd"
		});
	  }
	});
	 
 });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="form-group">
  <h5>Incidencia extemporánea</h5>
  <input type="checkbox" name="chk_out" id="chk_out" class="">
</div>

<div class="form-group">
  <h5>Fecha del incidente</h5>
  <input type="text" id="fecha" class="datepicker" readonly>
</div>
    
answered by 22.12.2016 / 01:12
source