Recover value from input data

Asked

Viewed 169 times

0

How do I recover input data value? My goal is value to match the date selected in the field.

Campo para filtrar

Filter field:

<div class="filt-nam">
        <h5>Filtrar Itinerários por Data: </h5>
      </div>
      <div class="row align-items-center">
        <div class="col-sm-6">
          <div class="input-group">
            <input type="date" class="form-control" id="dataInicio" value="" />
            <input type="date" class="form-control" id="dataFim" value="" />
            <div class="input-group-append">
              <button class="btn btn-outline-secondary" type="button" onclick="filtrarData()">Filtrar</button>
            </div>
          </div>
        </div>

JS file:

function filtrarData() {
    let dataInicio = document.getElementById('dataInicio')
    let dataFim = document.getElementById('dataFinal')

    console.log(dataInicio.value, dataFim.value)
};
  • 1

    You switched dataFim for dataFinal.

  • The end, what is the real purpose of the question? Is to correct the error of a single field, such as the Sam mentioned and the André Filipe responded or format the field, such as the Luiz Felipe answered? What is the error? What happens unexpectedly? You should aim to avoid questions like "kick"...

  • Let’s wait for the answer from Felipe Noka.

2 answers

2


According to the documentation, the <input> of the kind date will always return a string in format AAAA-MM-DD, that is, year, month and day.

You need to create a function to turn the date into the format AAAA-MM-DD for DD/MM/AAAA:

const field = document.querySelector('#date-field')

function formatDate(date) {
  const [, year, month, day] = date.match(/^(\d{4})-(\d{2})-(\d{2})$/)
  return `${day}/${month}/${year}`
}

field.addEventListener('change', (event) => {
  console.log(`Sem formatação: ${event.target.value}`)
  console.log(`Com formatação: ${formatDate(event.target.value)}`)
})
<input type="date" id="date-field" />

Reference:

2

How to recover input data value?

Making a brief analysis of your code vi that is structured correctly, however, in the second variable dataFim you’re giving a document.getElementById('dataFinal'), once that Id does not exist in your code HTML the console.log will launch the following exception as its variable dataFim will be void:

Uncaught Typeerror: Cannot read Property 'value' of null

You could change your code Javascript for:

let dataFim = document.getElementById('dataFim')

or your HTML for:

<input type="date" class="form-control" id="dataFinal" value="" />

Browser other questions tagged

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