Comparing fields from a form

Asked

Viewed 55 times

0

I have a form with the fields below. I need to compare the year of the field select with year of date informed via Javascript, and the year of date informed has to be identical to the year chosen, but I have not yet succeeded.

<label for="ano_licenca"><strong>ANO DA LICENCA</strong></label>
<select name="ano_licenca" id="ano_licenca" class="form-control">
    <option value="">SELECIONE</option>
    <option value="2017">2017</option>
    <option value="2018">2018</option>
</select> <br><br>

<label for="data_emissao"><strong>DATA EMISSAO *</strong></label>
<input type="date" name="data_emissao" id="data_emissao" class="form-control" onblur="comparadataano()" autofocus/><br><br/>

<script type="text/javascript">
    function comparadataano()
    {
        var ano_licenca = document.getElementById("ano_licenca");
        var data_emissao = document.getElementById("data_emissao");

        if (data_emissao.value > ano_licenca.value || data_emissao.value < ano_licenca.value) {
            alert("ERRO! O ANO INFORMADO, NAO ESTAR COM O MESMO ANO DA DATA DE EMISSAO");
            ano_licenca = document.getElementById('ano_licenca').value = '';
            data_emissao = document.getElementById('data_emissao').value = '';

        }
    }
</script>

1 answer

1

See example working:

function comparaDataAno() {
  var ano_licenca = document.getElementById("ano_licenca").value;
  var data_emissao = document.getElementById("data_emissao").value;
  var data = data_emissao.substr(0,4); // pega só o ano

  if (ano_licenca != data) {
	 alert("ERRO! O ANO INFORMADO, NAO ESTA COM O MESMO ANO DA DATA DE EMISSAO");
  } else {
	 alert("Datas válidas");
  }
}
<label for="ano_licenca"><strong>ANO DA LICENCA</strong></label>
<select name="ano_licenca" id="ano_licenca" class="form-control">
  <option value="">SELECIONE</option>
  <option value="2017">2017</option>
  <option value="2018">2018</option>
</select>

<label for="data_emissao"><strong>DATA EMISSAO *</strong></label>
<input type="date" name="data_emissao" id="data_emissao" class="form-control" onblur="comparaDataAno()"/>

VC needs to improve some things in your code:

1- Always put the function name with camelcase or use (_) for a better readability.

2- Your if you don’t have to test the conditions that way, with a simple (!=) you decrease the code.

3- The autofocus is not necessary because first you want the select be filled in.

  • Thanks friend! Thanks for the strength

Browser other questions tagged

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