I want to take the value of one form field and move on to another

Asked

Viewed 16 times

0

I tried to do it in JS

function diaSemana() {
  var data = new Date();
  var dia = data.getDay();
  var dias = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];

  var p = document.getElementById('campo').value = dias[dia];
  return p;
}
diaSemana();
<p>Estes são os respetivos campos, e queria pegar o valor da data e passar em simultâneo quando escolho um dia para campo de leitura.</p>
<form>
  <label>Data:</label>
  <input type="date" id="data">
  
  <label>Dia da Semana:</label>
  <input type="text" id="campo" readonly>
</form>

  
     function diaSemana() {     
       var data = new Date();
       var dia = data.getDay();
       var dias = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];     
       var p = document.getElementById('p').innerHTML = dias[dia];
       return p;
     }
    diaSemana();
  

1 answer

0

You can use the event onchange to know when the input date is changed and can update the field with the day of the week. See in the example below:

const inputData = document.querySelector('#data');
const inputDiaSemana = document.querySelector('#campo');
const diasSemana = [
  'Domingo',
  'Segunda',
  'Terça',
  'Quarta',
  'Quinta', 
  'Sexta',
  'Sábado'
];

inputData.addEventListener('change', () => {
    const [dia, mes, ano] = inputData.value.split('/');
    const objDate = new Date(ano, mes - 1, dia);

    inputDiaSemana.value = diasSemana[objDate.getDay()]; 
});
<p>Estes são os respetivos campos,
e queria pegar o valor da data e passar
em simultâneo quando escolho um dia para
campo de leitura.</p>
<form>
  <label>Data:</label>
  <input type="date" id="data" placeholder="dd/mm/yyyy">
  
  <label>Dia da Semana:</label>
  <input type="text" id="campo" readonly>
</form>

  • I will implement the script, the year and the month will be dynamic with PHP.

  • Cool Willeu! Then this script should change a little bit. If there are issues post again, abs ;)

  • All right, Marcelo...

  • &#xA; const objDate = new Date(ano, mes - 1, dia); &#xA;&#xA; Wanted a recommendation on how to make this dynamic, tried and failed. I feel that this functionality should be created with JS in contrast to PHP, which I’ve already done, but it doesn’t have the interaction and accessibility that I wanted. I would be grateful, @Marcelovismari

  • I didn’t understand it very well. The value of objDate come from PHP? something like: const objDate = new Date(<%= $ano %>, <%= $mes %>, <%= $dia %>);?

Browser other questions tagged

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