Compare fields on a form

0

I have a form with the fields below. I need to compare the year of the field select with year of the date entered via JavaScript, and the year of the entered date must be identical to the year chosen, but not yet successful.

<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>
    
asked by anonymous 24.05.2018 / 16:42

1 answer

1

See the 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()"/>
  

You need to improve some things in your code:

     

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

     

2- Your if does not need to test the conditions that way, with a simple (!=) you decrease the code

.

     

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

    
24.05.2018 / 17:35