Popular select based on a json date

Asked

Viewed 1,624 times

2

I have a bootstrap and validated form right, but I need that when selecting a date on the datepicker, it automatically loads a select with JSON, and has 3 more selects need to be filled after this, and all dependent on each other, ex:

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

By default of backend need to do in JSON and Ajax.

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

Fiddle: http://jsfiddle.net/rubensoul/2671hn9n

my html code is 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 is like this:

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


?>

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

  • I searched in many forums and found nothing. I need is that when clicking on a specific date, load a select with json, understood?

  • To better understand, the code is here, after selecting the date ai starts to popular the selects, one after selecting the other. http://jsfiddle.net/rubensoul/2671hn9n/

  • Your jsFiddle is incomplete... Can you continue this jsFiddle -> http://jsfiddle.net/bt7ksttx/ and explain which part you can’t do? is to select a select from the choices of another or the part of communication with the server?

  • Hello @Sergio, I have a php file with json data, first I need that when clicking on the date it loads the data of json to the first field (region) based on the information of the date, and when clicking on region, populate the professional file, and then populate the time

1 answer

2


in your fiddle has a part of javascript:

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

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

The function shall be placed on:

$( "#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 call $('#calendario').text(this.value); is not necessary, we may need to verify the return of .bootstrapValidator() before executing the AJAX.

To modify other fields when one <select> the event shall be used onChange. Personally, I recommend using .bind() to assign events:

$('#regiao').bind('change', function(){
// $('#regiao').change(function(){ // também funcionará
  // incluir AJAX igual da sua função anterior
})
  • Hello, @Sanction Thank you so much for the reply, but could you help me and let me know where exactly I should put onSelect? I added after ajax ({, and continued not accessing.. I am Noob/beginner in json/ajax yet, I intend to improve more, but this job gave a break in me.. rsrs

  • @Rubensjunior edited the answer

  • Dude, it was really helpful, I wouldn’t have made it!! Thank you. Can you just ask me one more question? I use the same code ex: $('#id'). bind('change', Function(){ // for all selects that need to be populated? or do I have to change something else in each one?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.