Popular select based on a date in json

1

I have a bootstrap form and validated it right, but I need it when selecting a date in the datepicker, it automatically loads a select with JSON, and has 3 more selects need to be filled after this, and all dependent one another, eg:

I chose the date 5/17/2015, it opens an information in select below, which opens other information after selected, and so on.

By default the backend needs to do in JSON and Ajax.

Can someone help me with this or show me the best way for me to do it?

Fiddle: link

My html code looks like this:

        <script type="text/javascript">

          /** O dia que gostaria de desabilitar no calendário */
          var disableddates = ["5-6-2015", "7-7-2015", "8-8-2015", "13-7-2015"];

          function DisableSpecificDates(date) {


            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            // Formato da desabilitada dd-mm-yyyy 

            var currentdate =  d + '-' + (m + 1) + '-' + y ;

            // Vamos agora verificar se a data pertence a disableddates matriz
            for (var i = 0; i < disableddates.length; i++) {

              // Agora, verifique quais datas existem na matriz datas e ativa no calendário. 
              if ($.inArray(currentdate, disableddates) != -1 ) {
                  return [true];
              } else {
                  return [false];
              }

            }

            // No caso de a data não está presente na matriz deficientes , vamos agora verificar se é um fim de semana .
            // com a função noWeekends
            var weekenddate = $.datepicker.noWeekends(date);
            return weekenddate; 

          }


          $(function() {
            $( "#calendario" ).datepicker({
              beforeShowDay: DisableSpecificDates,
              minDate: 0,
              dateFormat: 'dd/mm/yy',
              //validação da data caso preenchimento errado ou vázio
              onSelect: function (calendario, inst) {
                $('#calendario').text(this.value);
                $('#defaultForm').bootstrapValidator('revalidateField', 'calendario');
              },
              // tradução do calendário
              dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
              dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
              dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
              monthNames: [  'Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
              monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
              nextText: 'Próximo',
              prevText: 'Anterior'
            });
          });

$(document).ready(function(){
   $("#calendario").select(function(){
      $.ajax({
         type: "POST",
         url: "teste.php",
         data: {calendario: $("#calendario").val()},
         dataType: "json",
         success: function(json){
            var options = "";
            $.each(json, function(key, value){
               options += '<option value="' + key + '">' + value + '</option>';
            });
            $("#regiao").html(options);
         }
      });
   });
});

        </script> 
        
        <script>
 $('#regiao').change(function(){ 
     $.ajax({
         type: "POST",
         url: "teste2.php",
         data: {regiao: $("#regiao").val()},
         dataType: "json",
         success: function(json){
            var options = "";
            $.each(json, function(key, value){
               options += '<option value="' + key + '">' + value + '</option>';
            });
            $("#profissional").html(options);
         }
      });
   });


        </script> 
    <form id="defaultForm" action="lista-atendimento.html" method="POST">
      <div class="form-group">
        <label control-label>* Data da consulta:</label>
        <input id="calendario" type="text" class="date-picker form-control2" name="calendario" placeholder="Data da consulta" />
        <label for="calendario" class="input-group-addon2 btn" style="margin: -3px 0 0 -4px;"><span class="glyphicon glyphicon-calendar"></span> </label>

      </div>
      <div class="form-group">
        <label>* Região:</label>
        <select class="form-control2" name="regiao" id="regiao">
          <option>Selecione a Data</option>
        </select>
        
        
      </div>
      <div class="form-group">
        <label>* Profissional:</label>
        <select class="form-control2" name="profissional">
          <option>Selecione uma região</option>
        </select>
      </div>
      <div class="form-group">
        <label>* Horários Disponíveis:</label>
        <select class="form-control2" name="horarios">
          <option>17:00</option>
          <option>18:00</option>
        </select>
      </div>

In my php json it looks like this:

<?php echo json_encode(array(
// id e nome
'0'=>'Selecione Região',
'1'=>'Barueri',
'2'=>'Paulista')); 


?>

I have a php file with the json data, first I need it to click on the date it loads the json data into the first field (region) based on the date information, and when clicking on the region, populate the professional file , and then populate the time

    
asked by anonymous 17.06.2015 / 07:16

1 answer

1

In your fiddle you have a part of javascript:

$(document).ready(function(){ // linha 61 no fiddle
  $("#calendario").select(function(){
    // seu código iniciado por $.ajax({
  }
}

In this section the function to execute when the date is selected is added, but this function must be placed in onSelect of datepicker .

The function should be placed in:

$( "#calendario" ).datepicker({ // linha 40 no fiddle
  // opções do .datepicker
  onSelect: function(){
    // seu código $.ajax()
  }
});

The function already exists, so you need to merge the content. The $('#calendario').text(this.value); call is not required, you may need to check the .bootstrapValidator() return before running AJAX.

To modify other fields when a <select> is changed, the onChange event must be used. I personally recommend using .bind() to assign events:

$('#regiao').bind('change', function(){
// $('#regiao').change(function(){ // também funcionará
  // incluir AJAX igual da sua função anterior
})
    
17.06.2015 / 14:08