Fill in input with the day of the week according to the date in the previous input

Asked

Viewed 263 times

1

I created two inputs. The first one assigned the pre-filled date in this way:

<strong><label for="Data">Data Reserva</label></strong>
<input type="date" id="Data" name="Data" value="<?php echo date("Y-m-d");?>"/>

Wanted the second input to fill in the day of the week according to the date I selected in the previous input:

<strong><label for="Dia">Dia da Semana/Utilização</label></strong>
<input type="text" id="Dia" name="Dia" style="width:220px"/>

1 answer

2


You can use an event change in the date input and insert the day of the week in the other input whenever you change it.

But you must use the object Date() to extract the day of the week from the date in the input. In case I split the date, which is in the format aaaa-mm-dd, to build the object Date(ano, mês, dia), and with .getDay() numerical value is obtained for the day of the week, which is called according to the position in the array:

$(function(){

   $("#Data").on("change", function(){

      var d = this.value.split("-");
      var data = new Date(d[0], d[1]-1, d[2]).getDay();
      var dia_semana = ['DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SÁB'][data];
      $("#Dia").val(dia_semana);

   }).change();

});

Working example:

$(function(){
   
   $("#Data").on("change", function(){
      
      var d = this.value.split("-");
      var data = new Date(d[0], d[1]-1, d[2]).getDay();
      var dia_semana = ['DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SÁB'][data];
      $("#Dia").val(dia_semana);
      
   }).change();
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong><label for="Data">Data Reserva</label></strong>
<input type="date" id="Data" name="Data" value="2019-04-23"/>
<br>
<strong><label for="Dia">Dia da Semana/Utilização</label></strong>
<input type="text" id="Dia" name="Dia" style="width:220px"/>

Browser other questions tagged

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